babylon.max.js 4.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. (function universalModuleDefinition(root, factory) {
  18. if(typeof exports === 'object' && typeof module === 'object')
  19. module.exports = factory();
  20. else if(typeof define === 'function' && define.amd)
  21. define("babylonjs", [], factory);
  22. else if(typeof exports === 'object')
  23. exports["babylonjs"] = factory();
  24. else {
  25. root["BABYLON"] = factory(root["BABYLON"]);
  26. }
  27. })(this, function() {
  28. "use strict";
  29. var BABYLON;
  30. (function (BABYLON) {
  31. /**
  32. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  33. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  34. */
  35. var EffectFallbacks = /** @class */ (function () {
  36. function EffectFallbacks() {
  37. this._defines = {};
  38. this._currentRank = 32;
  39. this._maxRank = -1;
  40. }
  41. /**
  42. * Removes the fallback from the bound mesh.
  43. */
  44. EffectFallbacks.prototype.unBindMesh = function () {
  45. this._mesh = null;
  46. };
  47. /**
  48. * Adds a fallback on the specified property.
  49. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  50. * @param define The name of the define in the shader
  51. */
  52. EffectFallbacks.prototype.addFallback = function (rank, define) {
  53. if (!this._defines[rank]) {
  54. if (rank < this._currentRank) {
  55. this._currentRank = rank;
  56. }
  57. if (rank > this._maxRank) {
  58. this._maxRank = rank;
  59. }
  60. this._defines[rank] = new Array();
  61. }
  62. this._defines[rank].push(define);
  63. };
  64. /**
  65. * Sets the mesh to use CPU skinning when needing to fallback.
  66. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  67. * @param mesh The mesh to use the fallbacks.
  68. */
  69. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  70. this._mesh = mesh;
  71. if (rank < this._currentRank) {
  72. this._currentRank = rank;
  73. }
  74. if (rank > this._maxRank) {
  75. this._maxRank = rank;
  76. }
  77. };
  78. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  79. /**
  80. * Checks to see if more fallbacks are still availible.
  81. */
  82. get: function () {
  83. return this._currentRank <= this._maxRank;
  84. },
  85. enumerable: true,
  86. configurable: true
  87. });
  88. /**
  89. * Removes the defines that shoould be removed when falling back.
  90. * @param currentDefines defines the current define statements for the shader.
  91. * @param effect defines the current effect we try to compile
  92. * @returns The resulting defines with defines of the current rank removed.
  93. */
  94. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  95. // First we try to switch to CPU skinning
  96. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  97. this._mesh.computeBonesUsingShaders = false;
  98. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  99. var scene = this._mesh.getScene();
  100. for (var index = 0; index < scene.meshes.length; index++) {
  101. var otherMesh = scene.meshes[index];
  102. if (!otherMesh.material) {
  103. continue;
  104. }
  105. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  106. continue;
  107. }
  108. if (otherMesh.material.getEffect() === effect) {
  109. otherMesh.computeBonesUsingShaders = false;
  110. }
  111. else {
  112. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  113. var subMesh = _a[_i];
  114. var subMeshEffect = subMesh.effect;
  115. if (subMeshEffect === effect) {
  116. otherMesh.computeBonesUsingShaders = false;
  117. break;
  118. }
  119. }
  120. }
  121. }
  122. }
  123. else {
  124. var currentFallbacks = this._defines[this._currentRank];
  125. if (currentFallbacks) {
  126. for (var index = 0; index < currentFallbacks.length; index++) {
  127. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  128. }
  129. }
  130. this._currentRank++;
  131. }
  132. return currentDefines;
  133. };
  134. return EffectFallbacks;
  135. }());
  136. BABYLON.EffectFallbacks = EffectFallbacks;
  137. /**
  138. * Options to be used when creating an effect.
  139. */
  140. var EffectCreationOptions = /** @class */ (function () {
  141. function EffectCreationOptions() {
  142. }
  143. return EffectCreationOptions;
  144. }());
  145. BABYLON.EffectCreationOptions = EffectCreationOptions;
  146. /**
  147. * Effect containing vertex and fragment shader that can be executed on an object.
  148. */
  149. var Effect = /** @class */ (function () {
  150. /**
  151. * Instantiates an effect.
  152. * An effect can be used to create/manage/execute vertex and fragment shaders.
  153. * @param baseName Name of the effect.
  154. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  155. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  156. * @param samplers List of sampler variables that will be passed to the shader.
  157. * @param engine Engine to be used to render the effect
  158. * @param defines Define statements to be added to the shader.
  159. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  160. * @param onCompiled Callback that will be called when the shader is compiled.
  161. * @param onError Callback that will be called if an error occurs during shader compilation.
  162. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  163. */
  164. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  165. if (samplers === void 0) { samplers = null; }
  166. if (defines === void 0) { defines = null; }
  167. if (fallbacks === void 0) { fallbacks = null; }
  168. if (onCompiled === void 0) { onCompiled = null; }
  169. if (onError === void 0) { onError = null; }
  170. var _this = this;
  171. /**
  172. * Unique ID of the effect.
  173. */
  174. this.uniqueId = 0;
  175. /**
  176. * Observable that will be called when the shader is compiled.
  177. */
  178. this.onCompileObservable = new BABYLON.Observable();
  179. /**
  180. * Observable that will be called if an error occurs during shader compilation.
  181. */
  182. this.onErrorObservable = new BABYLON.Observable();
  183. /**
  184. * Observable that will be called when effect is bound.
  185. */
  186. this.onBindObservable = new BABYLON.Observable();
  187. this._uniformBuffersNames = {};
  188. this._isReady = false;
  189. this._compilationError = "";
  190. this.name = baseName;
  191. if (attributesNamesOrOptions.attributes) {
  192. var options = attributesNamesOrOptions;
  193. this._engine = uniformsNamesOrEngine;
  194. this._attributesNames = options.attributes;
  195. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  196. this._samplers = options.samplers;
  197. this.defines = options.defines;
  198. this.onError = options.onError;
  199. this.onCompiled = options.onCompiled;
  200. this._fallbacks = options.fallbacks;
  201. this._indexParameters = options.indexParameters;
  202. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  203. if (options.uniformBuffersNames) {
  204. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  205. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  206. }
  207. }
  208. }
  209. else {
  210. this._engine = engine;
  211. this.defines = defines;
  212. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  213. this._samplers = samplers;
  214. this._attributesNames = attributesNamesOrOptions;
  215. this.onError = onError;
  216. this.onCompiled = onCompiled;
  217. this._indexParameters = indexParameters;
  218. this._fallbacks = fallbacks;
  219. }
  220. this.uniqueId = Effect._uniqueIdSeed++;
  221. if (this._getFromCache(baseName)) {
  222. this._prepareEffect();
  223. return;
  224. }
  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. var finalVertexCode;
  246. this._loadVertexShaderAsync(vertexSource)
  247. .then(function (vertexCode) {
  248. return _this._processIncludesAsync(vertexCode);
  249. })
  250. .then(function (vertexCodeWithIncludes) {
  251. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  252. return _this._loadFragmentShaderAsync(fragmentSource);
  253. })
  254. .then(function (fragmentCode) {
  255. return _this._processIncludesAsync(fragmentCode);
  256. })
  257. .then(function (fragmentCodeWithIncludes) {
  258. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  259. if (baseName) {
  260. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  261. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  262. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  263. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  264. }
  265. else {
  266. _this._vertexSourceCode = finalVertexCode;
  267. _this._fragmentSourceCode = migratedFragmentCode;
  268. }
  269. _this._setInCache(baseName);
  270. _this._prepareEffect();
  271. });
  272. }
  273. Effect.prototype._getSourceCacheKey = function (baseName) {
  274. var cacheKey = baseName;
  275. if (this._indexParameters) {
  276. for (var key in this._indexParameters) {
  277. if (this._indexParameters.hasOwnProperty(key)) {
  278. cacheKey += "|";
  279. cacheKey += key;
  280. cacheKey += "_";
  281. cacheKey += this._indexParameters[key];
  282. }
  283. }
  284. }
  285. return cacheKey;
  286. };
  287. Effect.prototype._getFromCache = function (baseName) {
  288. if (typeof baseName !== "string") {
  289. return false;
  290. }
  291. var cacheKey = this._getSourceCacheKey(baseName);
  292. var sources = Effect._sourceCache[cacheKey];
  293. if (!sources) {
  294. return false;
  295. }
  296. this._vertexSourceCode = sources.vertex;
  297. this._fragmentSourceCode = sources.fragment;
  298. return true;
  299. };
  300. Effect.prototype._setInCache = function (baseName) {
  301. if (typeof baseName !== "string") {
  302. return;
  303. }
  304. var cacheKey = this._getSourceCacheKey(baseName);
  305. Effect._sourceCache[cacheKey] = {
  306. vertex: this._vertexSourceCode,
  307. fragment: this._fragmentSourceCode
  308. };
  309. };
  310. Object.defineProperty(Effect.prototype, "key", {
  311. /**
  312. * Unique key for this effect
  313. */
  314. get: function () {
  315. return this._key;
  316. },
  317. enumerable: true,
  318. configurable: true
  319. });
  320. /**
  321. * If the effect has been compiled and prepared.
  322. * @returns if the effect is compiled and prepared.
  323. */
  324. Effect.prototype.isReady = function () {
  325. return this._isReady;
  326. };
  327. /**
  328. * The engine the effect was initialized with.
  329. * @returns the engine.
  330. */
  331. Effect.prototype.getEngine = function () {
  332. return this._engine;
  333. };
  334. /**
  335. * The compiled webGL program for the effect
  336. * @returns the webGL program.
  337. */
  338. Effect.prototype.getProgram = function () {
  339. return this._program;
  340. };
  341. /**
  342. * The set of names of attribute variables for the shader.
  343. * @returns An array of attribute names.
  344. */
  345. Effect.prototype.getAttributesNames = function () {
  346. return this._attributesNames;
  347. };
  348. /**
  349. * Returns the attribute at the given index.
  350. * @param index The index of the attribute.
  351. * @returns The location of the attribute.
  352. */
  353. Effect.prototype.getAttributeLocation = function (index) {
  354. return this._attributes[index];
  355. };
  356. /**
  357. * Returns the attribute based on the name of the variable.
  358. * @param name of the attribute to look up.
  359. * @returns the attribute location.
  360. */
  361. Effect.prototype.getAttributeLocationByName = function (name) {
  362. var index = this._attributesNames.indexOf(name);
  363. return this._attributes[index];
  364. };
  365. /**
  366. * The number of attributes.
  367. * @returns the numnber of attributes.
  368. */
  369. Effect.prototype.getAttributesCount = function () {
  370. return this._attributes.length;
  371. };
  372. /**
  373. * Gets the index of a uniform variable.
  374. * @param uniformName of the uniform to look up.
  375. * @returns the index.
  376. */
  377. Effect.prototype.getUniformIndex = function (uniformName) {
  378. return this._uniformsNames.indexOf(uniformName);
  379. };
  380. /**
  381. * Returns the attribute based on the name of the variable.
  382. * @param uniformName of the uniform to look up.
  383. * @returns the location of the uniform.
  384. */
  385. Effect.prototype.getUniform = function (uniformName) {
  386. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  387. };
  388. /**
  389. * Returns an array of sampler variable names
  390. * @returns The array of sampler variable neames.
  391. */
  392. Effect.prototype.getSamplers = function () {
  393. return this._samplers;
  394. };
  395. /**
  396. * The error from the last compilation.
  397. * @returns the error string.
  398. */
  399. Effect.prototype.getCompilationError = function () {
  400. return this._compilationError;
  401. };
  402. /**
  403. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  404. * @param func The callback to be used.
  405. */
  406. Effect.prototype.executeWhenCompiled = function (func) {
  407. if (this.isReady()) {
  408. func(this);
  409. return;
  410. }
  411. this.onCompileObservable.add(function (effect) {
  412. func(effect);
  413. });
  414. };
  415. /** @ignore */
  416. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  417. if (BABYLON.Tools.IsWindowObjectExist()) {
  418. // DOM element ?
  419. if (vertex instanceof HTMLElement) {
  420. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  421. return Promise.resolve(vertexCode);
  422. }
  423. }
  424. // Base64 encoded ?
  425. if (vertex.substr(0, 7) === "base64:") {
  426. var vertexBinary = window.atob(vertex.substr(7));
  427. return Promise.resolve(vertexBinary);
  428. }
  429. // Is in local store ?
  430. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  431. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  432. }
  433. var vertexShaderUrl;
  434. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  435. vertexShaderUrl = vertex;
  436. }
  437. else {
  438. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  439. }
  440. // Vertex shader
  441. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  442. };
  443. /** @ignore */
  444. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  445. if (BABYLON.Tools.IsWindowObjectExist()) {
  446. // DOM element ?
  447. if (fragment instanceof HTMLElement) {
  448. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  449. return Promise.resolve(fragmentCode);
  450. }
  451. }
  452. // Base64 encoded ?
  453. if (fragment.substr(0, 7) === "base64:") {
  454. var fragmentBinary = window.atob(fragment.substr(7));
  455. return Promise.resolve(fragmentBinary);
  456. }
  457. // Is in local store ?
  458. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  459. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  460. }
  461. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  462. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  463. }
  464. var fragmentShaderUrl;
  465. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  466. fragmentShaderUrl = fragment;
  467. }
  468. else {
  469. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  470. }
  471. // Fragment shader
  472. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  473. };
  474. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  475. // Rebuild shaders source code
  476. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  477. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  478. vertexCode = prefix + vertexCode;
  479. fragmentCode = prefix + fragmentCode;
  480. // Number lines of shaders source code
  481. var i = 2;
  482. var regex = /\n/gm;
  483. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  484. i = 2;
  485. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  486. // Dump shaders name and formatted source code
  487. if (this.name.vertexElement) {
  488. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  489. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  490. }
  491. else if (this.name.vertex) {
  492. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  493. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  494. }
  495. else {
  496. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  497. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  498. }
  499. };
  500. ;
  501. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  502. var preparedSourceCode = this._processPrecision(sourceCode);
  503. if (this._engine.webGLVersion == 1) {
  504. return preparedSourceCode;
  505. }
  506. // Already converted
  507. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  508. return preparedSourceCode.replace("#version 300 es", "");
  509. }
  510. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  511. // Remove extensions
  512. // #extension GL_OES_standard_derivatives : enable
  513. // #extension GL_EXT_shader_texture_lod : enable
  514. // #extension GL_EXT_frag_depth : enable
  515. // #extension GL_EXT_draw_buffers : require
  516. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  517. var result = preparedSourceCode.replace(regex, "");
  518. // Migrate to GLSL v300
  519. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  520. result = result.replace(/attribute[ \t]/g, "in ");
  521. result = result.replace(/[ \t]attribute/g, " in");
  522. if (isFragment) {
  523. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  524. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  525. result = result.replace(/texture2D\s*\(/g, "texture(");
  526. result = result.replace(/textureCube\s*\(/g, "texture(");
  527. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  528. result = result.replace(/gl_FragColor/g, "glFragColor");
  529. result = result.replace(/gl_FragData/g, "glFragData");
  530. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  531. }
  532. return result;
  533. };
  534. Effect.prototype._processIncludesAsync = function (sourceCode) {
  535. var _this = this;
  536. return new Promise(function (resolve, reject) {
  537. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  538. var match = regex.exec(sourceCode);
  539. var returnValue = sourceCode;
  540. while (match != null) {
  541. var includeFile = match[1];
  542. // Uniform declaration
  543. if (includeFile.indexOf("__decl__") !== -1) {
  544. includeFile = includeFile.replace(/__decl__/, "");
  545. if (_this._engine.supportsUniformBuffers) {
  546. includeFile = includeFile.replace(/Vertex/, "Ubo");
  547. includeFile = includeFile.replace(/Fragment/, "Ubo");
  548. }
  549. includeFile = includeFile + "Declaration";
  550. }
  551. if (Effect.IncludesShadersStore[includeFile]) {
  552. // Substitution
  553. var includeContent = Effect.IncludesShadersStore[includeFile];
  554. if (match[2]) {
  555. var splits = match[3].split(",");
  556. for (var index = 0; index < splits.length; index += 2) {
  557. var source = new RegExp(splits[index], "g");
  558. var dest = splits[index + 1];
  559. includeContent = includeContent.replace(source, dest);
  560. }
  561. }
  562. if (match[4]) {
  563. var indexString = match[5];
  564. if (indexString.indexOf("..") !== -1) {
  565. var indexSplits = indexString.split("..");
  566. var minIndex = parseInt(indexSplits[0]);
  567. var maxIndex = parseInt(indexSplits[1]);
  568. var sourceIncludeContent = includeContent.slice(0);
  569. includeContent = "";
  570. if (isNaN(maxIndex)) {
  571. maxIndex = _this._indexParameters[indexSplits[1]];
  572. }
  573. for (var i = minIndex; i < maxIndex; i++) {
  574. if (!_this._engine.supportsUniformBuffers) {
  575. // Ubo replacement
  576. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  577. return p1 + "{X}";
  578. });
  579. }
  580. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  581. }
  582. }
  583. else {
  584. if (!_this._engine.supportsUniformBuffers) {
  585. // Ubo replacement
  586. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  587. return p1 + "{X}";
  588. });
  589. }
  590. includeContent = includeContent.replace(/\{X\}/g, indexString);
  591. }
  592. }
  593. // Replace
  594. returnValue = returnValue.replace(match[0], includeContent);
  595. }
  596. else {
  597. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  598. _this._engine._loadFileAsync(includeShaderUrl)
  599. .then(function (fileContent) {
  600. Effect.IncludesShadersStore[includeFile] = fileContent;
  601. return _this._processIncludesAsync(returnValue);
  602. })
  603. .then(function (returnValue) {
  604. resolve(returnValue);
  605. });
  606. return;
  607. }
  608. match = regex.exec(sourceCode);
  609. }
  610. resolve(returnValue);
  611. });
  612. };
  613. Effect.prototype._processPrecision = function (source) {
  614. if (source.indexOf("precision highp float") === -1) {
  615. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  616. source = "precision mediump float;\n" + source;
  617. }
  618. else {
  619. source = "precision highp float;\n" + source;
  620. }
  621. }
  622. else {
  623. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  624. source = source.replace("precision highp float", "precision mediump float");
  625. }
  626. }
  627. return source;
  628. };
  629. /**
  630. * Recompiles the webGL program
  631. * @param vertexSourceCode The source code for the vertex shader.
  632. * @param fragmentSourceCode The source code for the fragment shader.
  633. * @param onCompiled Callback called when completed.
  634. * @param onError Callback called on error.
  635. */
  636. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  637. var _this = this;
  638. this._isReady = false;
  639. this._vertexSourceCodeOverride = vertexSourceCode;
  640. this._fragmentSourceCodeOverride = fragmentSourceCode;
  641. this.onError = function (effect, error) {
  642. if (onError) {
  643. onError(error);
  644. }
  645. };
  646. this.onCompiled = function () {
  647. var scenes = _this.getEngine().scenes;
  648. for (var i = 0; i < scenes.length; i++) {
  649. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  650. }
  651. if (onCompiled) {
  652. onCompiled(_this._program);
  653. }
  654. };
  655. this._fallbacks = null;
  656. this._prepareEffect();
  657. };
  658. /**
  659. * Gets the uniform locations of the the specified variable names
  660. * @param names THe names of the variables to lookup.
  661. * @returns Array of locations in the same order as variable names.
  662. */
  663. Effect.prototype.getSpecificUniformLocations = function (names) {
  664. var engine = this._engine;
  665. return engine.getUniforms(this._program, names);
  666. };
  667. /**
  668. * Prepares the effect
  669. */
  670. Effect.prototype._prepareEffect = function () {
  671. var attributesNames = this._attributesNames;
  672. var defines = this.defines;
  673. var fallbacks = this._fallbacks;
  674. this._valueCache = {};
  675. var previousProgram = this._program;
  676. try {
  677. var engine = this._engine;
  678. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  679. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  680. }
  681. else {
  682. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  683. }
  684. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  685. if (engine.supportsUniformBuffers) {
  686. for (var name in this._uniformBuffersNames) {
  687. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  688. }
  689. }
  690. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  691. this._attributes = engine.getAttributes(this._program, attributesNames);
  692. var index;
  693. for (index = 0; index < this._samplers.length; index++) {
  694. var sampler = this.getUniform(this._samplers[index]);
  695. if (sampler == null) {
  696. this._samplers.splice(index, 1);
  697. index--;
  698. }
  699. }
  700. engine.bindSamplers(this);
  701. this._compilationError = "";
  702. this._isReady = true;
  703. if (this.onCompiled) {
  704. this.onCompiled(this);
  705. }
  706. this.onCompileObservable.notifyObservers(this);
  707. this.onCompileObservable.clear();
  708. // Unbind mesh reference in fallbacks
  709. if (this._fallbacks) {
  710. this._fallbacks.unBindMesh();
  711. }
  712. if (previousProgram) {
  713. this.getEngine()._deleteProgram(previousProgram);
  714. }
  715. }
  716. catch (e) {
  717. this._compilationError = e.message;
  718. // Let's go through fallbacks then
  719. BABYLON.Tools.Error("Unable to compile effect:");
  720. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  721. return " " + uniform;
  722. }));
  723. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  724. return " " + attribute;
  725. }));
  726. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  727. BABYLON.Tools.Error("Error: " + this._compilationError);
  728. if (previousProgram) {
  729. this._program = previousProgram;
  730. this._isReady = true;
  731. if (this.onError) {
  732. this.onError(this, this._compilationError);
  733. }
  734. this.onErrorObservable.notifyObservers(this);
  735. }
  736. if (fallbacks && fallbacks.isMoreFallbacks) {
  737. BABYLON.Tools.Error("Trying next fallback.");
  738. this.defines = fallbacks.reduce(this.defines, this);
  739. this._prepareEffect();
  740. }
  741. else {
  742. if (this.onError) {
  743. this.onError(this, this._compilationError);
  744. }
  745. this.onErrorObservable.notifyObservers(this);
  746. this.onErrorObservable.clear();
  747. // Unbind mesh reference in fallbacks
  748. if (this._fallbacks) {
  749. this._fallbacks.unBindMesh();
  750. }
  751. }
  752. }
  753. };
  754. Object.defineProperty(Effect.prototype, "isSupported", {
  755. /**
  756. * Checks if the effect is supported. (Must be called after compilation)
  757. */
  758. get: function () {
  759. return this._compilationError === "";
  760. },
  761. enumerable: true,
  762. configurable: true
  763. });
  764. /**
  765. * Binds a texture to the engine to be used as output of the shader.
  766. * @param channel Name of the output variable.
  767. * @param texture Texture to bind.
  768. */
  769. Effect.prototype._bindTexture = function (channel, texture) {
  770. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  771. };
  772. /**
  773. * Sets a texture on the engine to be used in the shader.
  774. * @param channel Name of the sampler variable.
  775. * @param texture Texture to set.
  776. */
  777. Effect.prototype.setTexture = function (channel, texture) {
  778. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  779. };
  780. /**
  781. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  782. * @param channel Name of the sampler variable.
  783. * @param texture Texture to set.
  784. */
  785. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  786. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  787. };
  788. /**
  789. * Sets an array of textures on the engine to be used in the shader.
  790. * @param channel Name of the variable.
  791. * @param textures Textures to set.
  792. */
  793. Effect.prototype.setTextureArray = function (channel, textures) {
  794. if (this._samplers.indexOf(channel + "Ex") === -1) {
  795. var initialPos = this._samplers.indexOf(channel);
  796. for (var index = 1; index < textures.length; index++) {
  797. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  798. }
  799. }
  800. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  801. };
  802. /**
  803. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  804. * 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)
  805. * @param channel Name of the sampler variable.
  806. * @param postProcess Post process to get the input texture from.
  807. */
  808. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  809. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  810. };
  811. /**
  812. * Sets the output texture of the passed in post process to be input of this effect.
  813. * @param channel Name of the sampler variable.
  814. * @param postProcess Post process to get the output texture from.
  815. */
  816. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  817. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  818. };
  819. /** @ignore */
  820. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  821. var cache = this._valueCache[uniformName];
  822. var flag = matrix.updateFlag;
  823. if (cache !== undefined && cache === flag) {
  824. return false;
  825. }
  826. this._valueCache[uniformName] = flag;
  827. return true;
  828. };
  829. /** @ignore */
  830. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  831. var cache = this._valueCache[uniformName];
  832. if (!cache) {
  833. cache = [x, y];
  834. this._valueCache[uniformName] = cache;
  835. return true;
  836. }
  837. var changed = false;
  838. if (cache[0] !== x) {
  839. cache[0] = x;
  840. changed = true;
  841. }
  842. if (cache[1] !== y) {
  843. cache[1] = y;
  844. changed = true;
  845. }
  846. return changed;
  847. };
  848. /** @ignore */
  849. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  850. var cache = this._valueCache[uniformName];
  851. if (!cache) {
  852. cache = [x, y, z];
  853. this._valueCache[uniformName] = cache;
  854. return true;
  855. }
  856. var changed = false;
  857. if (cache[0] !== x) {
  858. cache[0] = x;
  859. changed = true;
  860. }
  861. if (cache[1] !== y) {
  862. cache[1] = y;
  863. changed = true;
  864. }
  865. if (cache[2] !== z) {
  866. cache[2] = z;
  867. changed = true;
  868. }
  869. return changed;
  870. };
  871. /** @ignore */
  872. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  873. var cache = this._valueCache[uniformName];
  874. if (!cache) {
  875. cache = [x, y, z, w];
  876. this._valueCache[uniformName] = cache;
  877. return true;
  878. }
  879. var changed = false;
  880. if (cache[0] !== x) {
  881. cache[0] = x;
  882. changed = true;
  883. }
  884. if (cache[1] !== y) {
  885. cache[1] = y;
  886. changed = true;
  887. }
  888. if (cache[2] !== z) {
  889. cache[2] = z;
  890. changed = true;
  891. }
  892. if (cache[3] !== w) {
  893. cache[3] = w;
  894. changed = true;
  895. }
  896. return changed;
  897. };
  898. /**
  899. * Binds a buffer to a uniform.
  900. * @param buffer Buffer to bind.
  901. * @param name Name of the uniform variable to bind to.
  902. */
  903. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  904. var bufferName = this._uniformBuffersNames[name];
  905. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  906. return;
  907. }
  908. Effect._baseCache[bufferName] = buffer;
  909. this._engine.bindUniformBufferBase(buffer, bufferName);
  910. };
  911. /**
  912. * Binds block to a uniform.
  913. * @param blockName Name of the block to bind.
  914. * @param index Index to bind.
  915. */
  916. Effect.prototype.bindUniformBlock = function (blockName, index) {
  917. this._engine.bindUniformBlock(this._program, blockName, index);
  918. };
  919. /**
  920. * Sets an interger value on a uniform variable.
  921. * @param uniformName Name of the variable.
  922. * @param value Value to be set.
  923. * @returns this effect.
  924. */
  925. Effect.prototype.setInt = function (uniformName, value) {
  926. var cache = this._valueCache[uniformName];
  927. if (cache !== undefined && cache === value)
  928. return this;
  929. this._valueCache[uniformName] = value;
  930. this._engine.setInt(this.getUniform(uniformName), value);
  931. return this;
  932. };
  933. /**
  934. * Sets an int array on a uniform variable.
  935. * @param uniformName Name of the variable.
  936. * @param array array to be set.
  937. * @returns this effect.
  938. */
  939. Effect.prototype.setIntArray = function (uniformName, array) {
  940. this._valueCache[uniformName] = null;
  941. this._engine.setIntArray(this.getUniform(uniformName), array);
  942. return this;
  943. };
  944. /**
  945. * 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)
  946. * @param uniformName Name of the variable.
  947. * @param array array to be set.
  948. * @returns this effect.
  949. */
  950. Effect.prototype.setIntArray2 = function (uniformName, array) {
  951. this._valueCache[uniformName] = null;
  952. this._engine.setIntArray2(this.getUniform(uniformName), array);
  953. return this;
  954. };
  955. /**
  956. * 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)
  957. * @param uniformName Name of the variable.
  958. * @param array array to be set.
  959. * @returns this effect.
  960. */
  961. Effect.prototype.setIntArray3 = function (uniformName, array) {
  962. this._valueCache[uniformName] = null;
  963. this._engine.setIntArray3(this.getUniform(uniformName), array);
  964. return this;
  965. };
  966. /**
  967. * 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)
  968. * @param uniformName Name of the variable.
  969. * @param array array to be set.
  970. * @returns this effect.
  971. */
  972. Effect.prototype.setIntArray4 = function (uniformName, array) {
  973. this._valueCache[uniformName] = null;
  974. this._engine.setIntArray4(this.getUniform(uniformName), array);
  975. return this;
  976. };
  977. /**
  978. * Sets an float array on a uniform variable.
  979. * @param uniformName Name of the variable.
  980. * @param array array to be set.
  981. * @returns this effect.
  982. */
  983. Effect.prototype.setFloatArray = function (uniformName, array) {
  984. this._valueCache[uniformName] = null;
  985. this._engine.setFloatArray(this.getUniform(uniformName), array);
  986. return this;
  987. };
  988. /**
  989. * 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)
  990. * @param uniformName Name of the variable.
  991. * @param array array to be set.
  992. * @returns this effect.
  993. */
  994. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  995. this._valueCache[uniformName] = null;
  996. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  997. return this;
  998. };
  999. /**
  1000. * 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)
  1001. * @param uniformName Name of the variable.
  1002. * @param array array to be set.
  1003. * @returns this effect.
  1004. */
  1005. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1006. this._valueCache[uniformName] = null;
  1007. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1008. return this;
  1009. };
  1010. /**
  1011. * 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)
  1012. * @param uniformName Name of the variable.
  1013. * @param array array to be set.
  1014. * @returns this effect.
  1015. */
  1016. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1017. this._valueCache[uniformName] = null;
  1018. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1019. return this;
  1020. };
  1021. /**
  1022. * Sets an array on a uniform variable.
  1023. * @param uniformName Name of the variable.
  1024. * @param array array to be set.
  1025. * @returns this effect.
  1026. */
  1027. Effect.prototype.setArray = function (uniformName, array) {
  1028. this._valueCache[uniformName] = null;
  1029. this._engine.setArray(this.getUniform(uniformName), array);
  1030. return this;
  1031. };
  1032. /**
  1033. * 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)
  1034. * @param uniformName Name of the variable.
  1035. * @param array array to be set.
  1036. * @returns this effect.
  1037. */
  1038. Effect.prototype.setArray2 = function (uniformName, array) {
  1039. this._valueCache[uniformName] = null;
  1040. this._engine.setArray2(this.getUniform(uniformName), array);
  1041. return this;
  1042. };
  1043. /**
  1044. * 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)
  1045. * @param uniformName Name of the variable.
  1046. * @param array array to be set.
  1047. * @returns this effect.
  1048. */
  1049. Effect.prototype.setArray3 = function (uniformName, array) {
  1050. this._valueCache[uniformName] = null;
  1051. this._engine.setArray3(this.getUniform(uniformName), array);
  1052. return this;
  1053. };
  1054. /**
  1055. * 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)
  1056. * @param uniformName Name of the variable.
  1057. * @param array array to be set.
  1058. * @returns this effect.
  1059. */
  1060. Effect.prototype.setArray4 = function (uniformName, array) {
  1061. this._valueCache[uniformName] = null;
  1062. this._engine.setArray4(this.getUniform(uniformName), array);
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets matrices on a uniform variable.
  1067. * @param uniformName Name of the variable.
  1068. * @param matrices matrices to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1072. if (!matrices) {
  1073. return this;
  1074. }
  1075. this._valueCache[uniformName] = null;
  1076. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1077. return this;
  1078. };
  1079. /**
  1080. * Sets matrix on a uniform variable.
  1081. * @param uniformName Name of the variable.
  1082. * @param matrix matrix to be set.
  1083. * @returns this effect.
  1084. */
  1085. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1086. if (this._cacheMatrix(uniformName, matrix)) {
  1087. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1088. }
  1089. return this;
  1090. };
  1091. /**
  1092. * 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)
  1093. * @param uniformName Name of the variable.
  1094. * @param matrix matrix to be set.
  1095. * @returns this effect.
  1096. */
  1097. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1098. this._valueCache[uniformName] = null;
  1099. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1100. return this;
  1101. };
  1102. /**
  1103. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1104. * @param uniformName Name of the variable.
  1105. * @param matrix matrix to be set.
  1106. * @returns this effect.
  1107. */
  1108. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1109. this._valueCache[uniformName] = null;
  1110. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a float on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param value value to be set.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setFloat = function (uniformName, value) {
  1120. var cache = this._valueCache[uniformName];
  1121. if (cache !== undefined && cache === value)
  1122. return this;
  1123. this._valueCache[uniformName] = value;
  1124. this._engine.setFloat(this.getUniform(uniformName), value);
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a boolean on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param bool value to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setBool = function (uniformName, bool) {
  1134. var cache = this._valueCache[uniformName];
  1135. if (cache !== undefined && cache === bool)
  1136. return this;
  1137. this._valueCache[uniformName] = bool;
  1138. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1139. return this;
  1140. };
  1141. /**
  1142. * Sets a Vector2 on a uniform variable.
  1143. * @param uniformName Name of the variable.
  1144. * @param vector2 vector2 to be set.
  1145. * @returns this effect.
  1146. */
  1147. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1148. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1149. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1150. }
  1151. return this;
  1152. };
  1153. /**
  1154. * Sets a float2 on a uniform variable.
  1155. * @param uniformName Name of the variable.
  1156. * @param x First float in float2.
  1157. * @param y Second float in float2.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1161. if (this._cacheFloat2(uniformName, x, y)) {
  1162. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Vector3 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param vector3 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1173. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1174. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a float3 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param x First float in float3.
  1182. * @param y Second float in float3.
  1183. * @param z Third float in float3.
  1184. * @returns this effect.
  1185. */
  1186. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1187. if (this._cacheFloat3(uniformName, x, y, z)) {
  1188. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1189. }
  1190. return this;
  1191. };
  1192. /**
  1193. * Sets a Vector4 on a uniform variable.
  1194. * @param uniformName Name of the variable.
  1195. * @param vector4 Value to be set.
  1196. * @returns this effect.
  1197. */
  1198. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1199. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1200. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1201. }
  1202. return this;
  1203. };
  1204. /**
  1205. * Sets a float4 on a uniform variable.
  1206. * @param uniformName Name of the variable.
  1207. * @param x First float in float4.
  1208. * @param y Second float in float4.
  1209. * @param z Third float in float4.
  1210. * @param w Fourth float in float4.
  1211. * @returns this effect.
  1212. */
  1213. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1214. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1215. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1216. }
  1217. return this;
  1218. };
  1219. /**
  1220. * Sets a Color3 on a uniform variable.
  1221. * @param uniformName Name of the variable.
  1222. * @param color3 Value to be set.
  1223. * @returns this effect.
  1224. */
  1225. Effect.prototype.setColor3 = function (uniformName, color3) {
  1226. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1227. this._engine.setColor3(this.getUniform(uniformName), color3);
  1228. }
  1229. return this;
  1230. };
  1231. /**
  1232. * Sets a Color4 on a uniform variable.
  1233. * @param uniformName Name of the variable.
  1234. * @param color3 Value to be set.
  1235. * @param alpha Alpha value to be set.
  1236. * @returns this effect.
  1237. */
  1238. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1239. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1240. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1241. }
  1242. return this;
  1243. };
  1244. /**
  1245. * Sets a Color4 on a uniform variable
  1246. * @param uniformName defines the name of the variable
  1247. * @param color4 defines the value to be set
  1248. * @returns this effect.
  1249. */
  1250. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1251. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1252. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1253. }
  1254. return this;
  1255. };
  1256. /**
  1257. * Resets the cache of effects.
  1258. */
  1259. Effect.ResetCache = function () {
  1260. Effect._baseCache = {};
  1261. };
  1262. Effect._uniqueIdSeed = 0;
  1263. Effect._baseCache = {};
  1264. Effect._sourceCache = {};
  1265. // Statics
  1266. /**
  1267. * Store of each shader (The can be looked up using effect.key)
  1268. */
  1269. Effect.ShadersStore = {};
  1270. /**
  1271. * Store of each included file for a shader (The can be looked up using effect.key)
  1272. */
  1273. Effect.IncludesShadersStore = {};
  1274. return Effect;
  1275. }());
  1276. BABYLON.Effect = Effect;
  1277. })(BABYLON || (BABYLON = {}));
  1278. //# sourceMappingURL=babylon.effect.js.map
  1279. "use strict";
  1280. //# sourceMappingURL=babylon.types.js.map
  1281. "use strict";
  1282. var BABYLON;
  1283. (function (BABYLON) {
  1284. var KeyboardEventTypes = /** @class */ (function () {
  1285. function KeyboardEventTypes() {
  1286. }
  1287. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1288. get: function () {
  1289. return KeyboardEventTypes._KEYDOWN;
  1290. },
  1291. enumerable: true,
  1292. configurable: true
  1293. });
  1294. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1295. get: function () {
  1296. return KeyboardEventTypes._KEYUP;
  1297. },
  1298. enumerable: true,
  1299. configurable: true
  1300. });
  1301. KeyboardEventTypes._KEYDOWN = 0x01;
  1302. KeyboardEventTypes._KEYUP = 0x02;
  1303. return KeyboardEventTypes;
  1304. }());
  1305. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1306. var KeyboardInfo = /** @class */ (function () {
  1307. function KeyboardInfo(type, event) {
  1308. this.type = type;
  1309. this.event = event;
  1310. }
  1311. return KeyboardInfo;
  1312. }());
  1313. BABYLON.KeyboardInfo = KeyboardInfo;
  1314. /**
  1315. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1316. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1317. */
  1318. var KeyboardInfoPre = /** @class */ (function (_super) {
  1319. __extends(KeyboardInfoPre, _super);
  1320. function KeyboardInfoPre(type, event) {
  1321. var _this = _super.call(this, type, event) || this;
  1322. _this.skipOnPointerObservable = false;
  1323. return _this;
  1324. }
  1325. return KeyboardInfoPre;
  1326. }(KeyboardInfo));
  1327. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1328. })(BABYLON || (BABYLON = {}));
  1329. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1330. "use strict";
  1331. var BABYLON;
  1332. (function (BABYLON) {
  1333. var PointerEventTypes = /** @class */ (function () {
  1334. function PointerEventTypes() {
  1335. }
  1336. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1337. get: function () {
  1338. return PointerEventTypes._POINTERDOWN;
  1339. },
  1340. enumerable: true,
  1341. configurable: true
  1342. });
  1343. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1344. get: function () {
  1345. return PointerEventTypes._POINTERUP;
  1346. },
  1347. enumerable: true,
  1348. configurable: true
  1349. });
  1350. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1351. get: function () {
  1352. return PointerEventTypes._POINTERMOVE;
  1353. },
  1354. enumerable: true,
  1355. configurable: true
  1356. });
  1357. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1358. get: function () {
  1359. return PointerEventTypes._POINTERWHEEL;
  1360. },
  1361. enumerable: true,
  1362. configurable: true
  1363. });
  1364. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1365. get: function () {
  1366. return PointerEventTypes._POINTERPICK;
  1367. },
  1368. enumerable: true,
  1369. configurable: true
  1370. });
  1371. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1372. get: function () {
  1373. return PointerEventTypes._POINTERTAP;
  1374. },
  1375. enumerable: true,
  1376. configurable: true
  1377. });
  1378. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1379. get: function () {
  1380. return PointerEventTypes._POINTERDOUBLETAP;
  1381. },
  1382. enumerable: true,
  1383. configurable: true
  1384. });
  1385. PointerEventTypes._POINTERDOWN = 0x01;
  1386. PointerEventTypes._POINTERUP = 0x02;
  1387. PointerEventTypes._POINTERMOVE = 0x04;
  1388. PointerEventTypes._POINTERWHEEL = 0x08;
  1389. PointerEventTypes._POINTERPICK = 0x10;
  1390. PointerEventTypes._POINTERTAP = 0x20;
  1391. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1392. return PointerEventTypes;
  1393. }());
  1394. BABYLON.PointerEventTypes = PointerEventTypes;
  1395. var PointerInfoBase = /** @class */ (function () {
  1396. function PointerInfoBase(type, event) {
  1397. this.type = type;
  1398. this.event = event;
  1399. }
  1400. return PointerInfoBase;
  1401. }());
  1402. BABYLON.PointerInfoBase = PointerInfoBase;
  1403. /**
  1404. * This class is used to store pointer related info for the onPrePointerObservable event.
  1405. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1406. */
  1407. var PointerInfoPre = /** @class */ (function (_super) {
  1408. __extends(PointerInfoPre, _super);
  1409. function PointerInfoPre(type, event, localX, localY) {
  1410. var _this = _super.call(this, type, event) || this;
  1411. _this.skipOnPointerObservable = false;
  1412. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1413. return _this;
  1414. }
  1415. return PointerInfoPre;
  1416. }(PointerInfoBase));
  1417. BABYLON.PointerInfoPre = PointerInfoPre;
  1418. /**
  1419. * This type contains all the data related to a pointer event in Babylon.js.
  1420. * 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.
  1421. */
  1422. var PointerInfo = /** @class */ (function (_super) {
  1423. __extends(PointerInfo, _super);
  1424. function PointerInfo(type, event, pickInfo) {
  1425. var _this = _super.call(this, type, event) || this;
  1426. _this.pickInfo = pickInfo;
  1427. return _this;
  1428. }
  1429. return PointerInfo;
  1430. }(PointerInfoBase));
  1431. BABYLON.PointerInfo = PointerInfo;
  1432. })(BABYLON || (BABYLON = {}));
  1433. //# sourceMappingURL=babylon.pointerEvents.js.map
  1434. "use strict";
  1435. var BABYLON;
  1436. (function (BABYLON) {
  1437. BABYLON.ToGammaSpace = 1 / 2.2;
  1438. BABYLON.ToLinearSpace = 2.2;
  1439. BABYLON.Epsilon = 0.001;
  1440. /**
  1441. * Class used to hold a RBG color
  1442. */
  1443. var Color3 = /** @class */ (function () {
  1444. /**
  1445. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1446. * @param r defines the red component (between 0 and 1, default is 0)
  1447. * @param g defines the green component (between 0 and 1, default is 0)
  1448. * @param b defines the blue component (between 0 and 1, default is 0)
  1449. */
  1450. function Color3(
  1451. /**
  1452. * Defines the red component (between 0 and 1, default is 0)
  1453. */
  1454. r,
  1455. /**
  1456. * Defines the green component (between 0 and 1, default is 0)
  1457. */
  1458. g,
  1459. /**
  1460. * Defines the blue component (between 0 and 1, default is 0)
  1461. */
  1462. b) {
  1463. if (r === void 0) { r = 0; }
  1464. if (g === void 0) { g = 0; }
  1465. if (b === void 0) { b = 0; }
  1466. this.r = r;
  1467. this.g = g;
  1468. this.b = b;
  1469. }
  1470. /**
  1471. * Creates a string with the Color3 current values
  1472. * @returns the string representation of the Color3 object
  1473. */
  1474. Color3.prototype.toString = function () {
  1475. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1476. };
  1477. /**
  1478. * Returns the string "Color3"
  1479. * @returns "Color3"
  1480. */
  1481. Color3.prototype.getClassName = function () {
  1482. return "Color3";
  1483. };
  1484. /**
  1485. * Compute the Color3 hash code
  1486. * @returns an unique number that can be used to hash Color3 objects
  1487. */
  1488. Color3.prototype.getHashCode = function () {
  1489. var hash = this.r || 0;
  1490. hash = (hash * 397) ^ (this.g || 0);
  1491. hash = (hash * 397) ^ (this.b || 0);
  1492. return hash;
  1493. };
  1494. // Operators
  1495. /**
  1496. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1497. * @param array defines the array where to store the r,g,b components
  1498. * @param index defines an optional index in the target array to define where to start storing values
  1499. * @returns the current Color3 object
  1500. */
  1501. Color3.prototype.toArray = function (array, index) {
  1502. if (index === undefined) {
  1503. index = 0;
  1504. }
  1505. array[index] = this.r;
  1506. array[index + 1] = this.g;
  1507. array[index + 2] = this.b;
  1508. return this;
  1509. };
  1510. /**
  1511. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1512. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1513. * @returns a new {BABYLON.Color4} object
  1514. */
  1515. Color3.prototype.toColor4 = function (alpha) {
  1516. if (alpha === void 0) { alpha = 1; }
  1517. return new Color4(this.r, this.g, this.b, alpha);
  1518. };
  1519. /**
  1520. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1521. * @returns the new array
  1522. */
  1523. Color3.prototype.asArray = function () {
  1524. var result = new Array();
  1525. this.toArray(result, 0);
  1526. return result;
  1527. };
  1528. /**
  1529. * Returns the luminance value
  1530. * @returns a float value
  1531. */
  1532. Color3.prototype.toLuminance = function () {
  1533. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1534. };
  1535. /**
  1536. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1537. * @param otherColor defines the second operand
  1538. * @returns the new Color3 object
  1539. */
  1540. Color3.prototype.multiply = function (otherColor) {
  1541. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1542. };
  1543. /**
  1544. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1545. * @param otherColor defines the second operand
  1546. * @param result defines the Color3 object where to store the result
  1547. * @returns the current Color3
  1548. */
  1549. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1550. result.r = this.r * otherColor.r;
  1551. result.g = this.g * otherColor.g;
  1552. result.b = this.b * otherColor.b;
  1553. return this;
  1554. };
  1555. /**
  1556. * Determines equality between Color3 objects
  1557. * @param otherColor defines the second operand
  1558. * @returns true if the rgb values are equal to the passed ones
  1559. */
  1560. Color3.prototype.equals = function (otherColor) {
  1561. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1562. };
  1563. /**
  1564. * Determines equality between the current Color3 object and a set of r,b,g values
  1565. * @param r defines the red component to check
  1566. * @param g defines the green component to check
  1567. * @param b defines the blue component to check
  1568. * @returns true if the rgb values are equal to the passed ones
  1569. */
  1570. Color3.prototype.equalsFloats = function (r, g, b) {
  1571. return this.r === r && this.g === g && this.b === b;
  1572. };
  1573. /**
  1574. * Multiplies in place each rgb value by scale
  1575. * @param scale defines the scaling factor
  1576. * @returns the updated Color3
  1577. */
  1578. Color3.prototype.scale = function (scale) {
  1579. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1580. };
  1581. /**
  1582. * Multiplies the rgb values by scale and stores the result into "result"
  1583. * @param scale defines the scaling factor
  1584. * @param result defines the Color3 object where to store the result
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.scaleToRef = function (scale, result) {
  1588. result.r = this.r * scale;
  1589. result.g = this.g * scale;
  1590. result.b = this.b * scale;
  1591. return this;
  1592. };
  1593. /**
  1594. * Scale the current Color3 values by a factor and add the result to a given Color3
  1595. * @param scale defines the scale factor
  1596. * @param result defines color to store the result into
  1597. * @returns the unmodified current Color3
  1598. */
  1599. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1600. result.r += this.r * scale;
  1601. result.g += this.g * scale;
  1602. result.b += this.b * scale;
  1603. return this;
  1604. };
  1605. /**
  1606. * Clamps the rgb values by the min and max values and stores the result into "result"
  1607. * @param min defines minimum clamping value (default is 0)
  1608. * @param max defines maximum clamping value (default is 1)
  1609. * @param result defines color to store the result into
  1610. * @returns the original Color3
  1611. */
  1612. Color3.prototype.clampToRef = function (min, max, result) {
  1613. if (min === void 0) { min = 0; }
  1614. if (max === void 0) { max = 1; }
  1615. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1616. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1617. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1618. return this;
  1619. };
  1620. /**
  1621. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1622. * @param otherColor defines the second operand
  1623. * @returns the new Color3
  1624. */
  1625. Color3.prototype.add = function (otherColor) {
  1626. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1627. };
  1628. /**
  1629. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1630. * @param otherColor defines the second operand
  1631. * @param result defines Color3 object to store the result into
  1632. * @returns the unmodified current Color3
  1633. */
  1634. Color3.prototype.addToRef = function (otherColor, result) {
  1635. result.r = this.r + otherColor.r;
  1636. result.g = this.g + otherColor.g;
  1637. result.b = this.b + otherColor.b;
  1638. return this;
  1639. };
  1640. /**
  1641. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1642. * @param otherColor defines the second operand
  1643. * @returns the new Color3
  1644. */
  1645. Color3.prototype.subtract = function (otherColor) {
  1646. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1647. };
  1648. /**
  1649. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1650. * @param otherColor defines the second operand
  1651. * @param result defines Color3 object to store the result into
  1652. * @returns the unmodified current Color3
  1653. */
  1654. Color3.prototype.subtractToRef = function (otherColor, result) {
  1655. result.r = this.r - otherColor.r;
  1656. result.g = this.g - otherColor.g;
  1657. result.b = this.b - otherColor.b;
  1658. return this;
  1659. };
  1660. /**
  1661. * Copy the current object
  1662. * @returns a new Color3 copied the current one
  1663. */
  1664. Color3.prototype.clone = function () {
  1665. return new Color3(this.r, this.g, this.b);
  1666. };
  1667. /**
  1668. * Copies the rgb values from the source in the current Color3
  1669. * @param source defines the source Color3 object
  1670. * @returns the updated Color3 object
  1671. */
  1672. Color3.prototype.copyFrom = function (source) {
  1673. this.r = source.r;
  1674. this.g = source.g;
  1675. this.b = source.b;
  1676. return this;
  1677. };
  1678. /**
  1679. * Updates the Color3 rgb values from the passed floats
  1680. * @param r defines the red component to read from
  1681. * @param g defines the green component to read from
  1682. * @param b defines the blue component to read from
  1683. * @returns the current Color3 object
  1684. */
  1685. Color3.prototype.copyFromFloats = function (r, g, b) {
  1686. this.r = r;
  1687. this.g = g;
  1688. this.b = b;
  1689. return this;
  1690. };
  1691. /**
  1692. * Updates the Color3 rgb values from the passed floats
  1693. * @param r defines the red component to read from
  1694. * @param g defines the green component to read from
  1695. * @param b defines the blue component to read from
  1696. * @returns the current Color3 object
  1697. */
  1698. Color3.prototype.set = function (r, g, b) {
  1699. return this.copyFromFloats(r, g, b);
  1700. };
  1701. /**
  1702. * Compute the Color3 hexadecimal code as a string
  1703. * @returns a string containing the hexadecimal representation of the Color3 object
  1704. */
  1705. Color3.prototype.toHexString = function () {
  1706. var intR = (this.r * 255) | 0;
  1707. var intG = (this.g * 255) | 0;
  1708. var intB = (this.b * 255) | 0;
  1709. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1710. };
  1711. /**
  1712. * Computes a new Color3 converted from the current one to linear space
  1713. * @returns a new Color3 object
  1714. */
  1715. Color3.prototype.toLinearSpace = function () {
  1716. var convertedColor = new Color3();
  1717. this.toLinearSpaceToRef(convertedColor);
  1718. return convertedColor;
  1719. };
  1720. /**
  1721. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1722. * @param convertedColor defines the Color3 object where to store the linear space version
  1723. * @returns the unmodified Color3
  1724. */
  1725. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1726. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1727. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1728. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1729. return this;
  1730. };
  1731. /**
  1732. * Computes a new Color3 converted from the current one to gamma space
  1733. * @returns a new Color3 object
  1734. */
  1735. Color3.prototype.toGammaSpace = function () {
  1736. var convertedColor = new Color3();
  1737. this.toGammaSpaceToRef(convertedColor);
  1738. return convertedColor;
  1739. };
  1740. /**
  1741. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1742. * @param convertedColor defines the Color3 object where to store the gamma space version
  1743. * @returns the unmodified Color3
  1744. */
  1745. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1746. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1747. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1748. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1749. return this;
  1750. };
  1751. // Statics
  1752. /**
  1753. * Creates a new Color3 from the string containing valid hexadecimal values
  1754. * @param hex defines a string containing valid hexadecimal values
  1755. * @returns a new Color3 object
  1756. */
  1757. Color3.FromHexString = function (hex) {
  1758. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1759. return new Color3(0, 0, 0);
  1760. }
  1761. var r = parseInt(hex.substring(1, 3), 16);
  1762. var g = parseInt(hex.substring(3, 5), 16);
  1763. var b = parseInt(hex.substring(5, 7), 16);
  1764. return Color3.FromInts(r, g, b);
  1765. };
  1766. /**
  1767. * Creates a new Vector3 from the starting index of the passed array
  1768. * @param array defines the source array
  1769. * @param offset defines an offset in the source array
  1770. * @returns a new Color3 object
  1771. */
  1772. Color3.FromArray = function (array, offset) {
  1773. if (offset === void 0) { offset = 0; }
  1774. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1775. };
  1776. /**
  1777. * Creates a new Color3 from integer values (< 256)
  1778. * @param r defines the red component to read from (value between 0 and 255)
  1779. * @param g defines the green component to read from (value between 0 and 255)
  1780. * @param b defines the blue component to read from (value between 0 and 255)
  1781. * @returns a new Color3 object
  1782. */
  1783. Color3.FromInts = function (r, g, b) {
  1784. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1785. };
  1786. /**
  1787. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1788. * @param start defines the start Color3 value
  1789. * @param end defines the end Color3 value
  1790. * @param amount defines the gradient value between start and end
  1791. * @returns a new Color3 object
  1792. */
  1793. Color3.Lerp = function (start, end, amount) {
  1794. var r = start.r + ((end.r - start.r) * amount);
  1795. var g = start.g + ((end.g - start.g) * amount);
  1796. var b = start.b + ((end.b - start.b) * amount);
  1797. return new Color3(r, g, b);
  1798. };
  1799. /**
  1800. * Returns a Color3 value containing a red color
  1801. * @returns a new Color3 object
  1802. */
  1803. Color3.Red = function () { return new Color3(1, 0, 0); };
  1804. /**
  1805. * Returns a Color3 value containing a green color
  1806. * @returns a new Color3 object
  1807. */
  1808. Color3.Green = function () { return new Color3(0, 1, 0); };
  1809. /**
  1810. * Returns a Color3 value containing a blue color
  1811. * @returns a new Color3 object
  1812. */
  1813. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1814. /**
  1815. * Returns a Color3 value containing a black color
  1816. * @returns a new Color3 object
  1817. */
  1818. Color3.Black = function () { return new Color3(0, 0, 0); };
  1819. /**
  1820. * Returns a Color3 value containing a white color
  1821. * @returns a new Color3 object
  1822. */
  1823. Color3.White = function () { return new Color3(1, 1, 1); };
  1824. /**
  1825. * Returns a Color3 value containing a purple color
  1826. * @returns a new Color3 object
  1827. */
  1828. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1829. /**
  1830. * Returns a Color3 value containing a magenta color
  1831. * @returns a new Color3 object
  1832. */
  1833. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1834. /**
  1835. * Returns a Color3 value containing a yellow color
  1836. * @returns a new Color3 object
  1837. */
  1838. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1839. /**
  1840. * Returns a Color3 value containing a gray color
  1841. * @returns a new Color3 object
  1842. */
  1843. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1844. /**
  1845. * Returns a Color3 value containing a teal color
  1846. * @returns a new Color3 object
  1847. */
  1848. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1849. /**
  1850. * Returns a Color3 value containing a random color
  1851. * @returns a new Color3 object
  1852. */
  1853. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1854. return Color3;
  1855. }());
  1856. BABYLON.Color3 = Color3;
  1857. /**
  1858. * Class used to hold a RBGA color
  1859. */
  1860. var Color4 = /** @class */ (function () {
  1861. /**
  1862. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1863. * @param r defines the red component (between 0 and 1, default is 0)
  1864. * @param g defines the green component (between 0 and 1, default is 0)
  1865. * @param b defines the blue component (between 0 and 1, default is 0)
  1866. * @param a defines the alpha component (between 0 and 1, default is 1)
  1867. */
  1868. function Color4(
  1869. /**
  1870. * Defines the red component (between 0 and 1, default is 0)
  1871. */
  1872. r,
  1873. /**
  1874. * Defines the green component (between 0 and 1, default is 0)
  1875. */
  1876. g,
  1877. /**
  1878. * Defines the blue component (between 0 and 1, default is 0)
  1879. */
  1880. b,
  1881. /**
  1882. * Defines the alpha component (between 0 and 1, default is 1)
  1883. */
  1884. a) {
  1885. if (r === void 0) { r = 0; }
  1886. if (g === void 0) { g = 0; }
  1887. if (b === void 0) { b = 0; }
  1888. if (a === void 0) { a = 1; }
  1889. this.r = r;
  1890. this.g = g;
  1891. this.b = b;
  1892. this.a = a;
  1893. }
  1894. // Operators
  1895. /**
  1896. * Adds in place the passed Color4 values to the current Color4 object
  1897. * @param right defines the second operand
  1898. * @returns the current updated Color4 object
  1899. */
  1900. Color4.prototype.addInPlace = function (right) {
  1901. this.r += right.r;
  1902. this.g += right.g;
  1903. this.b += right.b;
  1904. this.a += right.a;
  1905. return this;
  1906. };
  1907. /**
  1908. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1909. * @returns the new array
  1910. */
  1911. Color4.prototype.asArray = function () {
  1912. var result = new Array();
  1913. this.toArray(result, 0);
  1914. return result;
  1915. };
  1916. /**
  1917. * Stores from the starting index in the passed array the Color4 successive values
  1918. * @param array defines the array where to store the r,g,b components
  1919. * @param index defines an optional index in the target array to define where to start storing values
  1920. * @returns the current Color4 object
  1921. */
  1922. Color4.prototype.toArray = function (array, index) {
  1923. if (index === undefined) {
  1924. index = 0;
  1925. }
  1926. array[index] = this.r;
  1927. array[index + 1] = this.g;
  1928. array[index + 2] = this.b;
  1929. array[index + 3] = this.a;
  1930. return this;
  1931. };
  1932. /**
  1933. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1934. * @param right defines the second operand
  1935. * @returns a new Color4 object
  1936. */
  1937. Color4.prototype.add = function (right) {
  1938. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1939. };
  1940. /**
  1941. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1942. * @param right defines the second operand
  1943. * @returns a new Color4 object
  1944. */
  1945. Color4.prototype.subtract = function (right) {
  1946. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1947. };
  1948. /**
  1949. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1950. * @param right defines the second operand
  1951. * @param result defines the Color4 object where to store the result
  1952. * @returns the current Color4 object
  1953. */
  1954. Color4.prototype.subtractToRef = function (right, result) {
  1955. result.r = this.r - right.r;
  1956. result.g = this.g - right.g;
  1957. result.b = this.b - right.b;
  1958. result.a = this.a - right.a;
  1959. return this;
  1960. };
  1961. /**
  1962. * Creates a new Color4 with the current Color4 values multiplied by scale
  1963. * @param scale defines the scaling factor to apply
  1964. * @returns a new Color4 object
  1965. */
  1966. Color4.prototype.scale = function (scale) {
  1967. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1968. };
  1969. /**
  1970. * Multiplies the current Color4 values by scale and stores the result in "result"
  1971. * @param scale defines the scaling factor to apply
  1972. * @param result defines the Color4 object where to store the result
  1973. * @returns the current unmodified Color4
  1974. */
  1975. Color4.prototype.scaleToRef = function (scale, result) {
  1976. result.r = this.r * scale;
  1977. result.g = this.g * scale;
  1978. result.b = this.b * scale;
  1979. result.a = this.a * scale;
  1980. return this;
  1981. };
  1982. /**
  1983. * Scale the current Color4 values by a factor and add the result to a given Color4
  1984. * @param scale defines the scale factor
  1985. * @param result defines the Color4 object where to store the result
  1986. * @returns the unmodified current Color4
  1987. */
  1988. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1989. result.r += this.r * scale;
  1990. result.g += this.g * scale;
  1991. result.b += this.b * scale;
  1992. result.a += this.a * scale;
  1993. return this;
  1994. };
  1995. /**
  1996. * Clamps the rgb values by the min and max values and stores the result into "result"
  1997. * @param min defines minimum clamping value (default is 0)
  1998. * @param max defines maximum clamping value (default is 1)
  1999. * @param result defines color to store the result into.
  2000. * @returns the cuurent Color4
  2001. */
  2002. Color4.prototype.clampToRef = function (min, max, result) {
  2003. if (min === void 0) { min = 0; }
  2004. if (max === void 0) { max = 1; }
  2005. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2006. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2007. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2008. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2009. return this;
  2010. };
  2011. /**
  2012. * Multipy an Color4 value by another and return a new Color4 object
  2013. * @param color defines the Color4 value to multiply by
  2014. * @returns a new Color4 object
  2015. */
  2016. Color4.prototype.multiply = function (color) {
  2017. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2018. };
  2019. /**
  2020. * Multipy a Color4 value by another and push the result in a reference value
  2021. * @param color defines the Color4 value to multiply by
  2022. * @param result defines the Color4 to fill the result in
  2023. * @returns the result Color4
  2024. */
  2025. Color4.prototype.multiplyToRef = function (color, result) {
  2026. result.r = this.r * color.r;
  2027. result.g = this.g * color.g;
  2028. result.b = this.b * color.b;
  2029. result.a = this.a * color.a;
  2030. return result;
  2031. };
  2032. /**
  2033. * Creates a string with the Color4 current values
  2034. * @returns the string representation of the Color4 object
  2035. */
  2036. Color4.prototype.toString = function () {
  2037. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2038. };
  2039. /**
  2040. * Returns the string "Color4"
  2041. * @returns "Color4"
  2042. */
  2043. Color4.prototype.getClassName = function () {
  2044. return "Color4";
  2045. };
  2046. /**
  2047. * Compute the Color4 hash code
  2048. * @returns an unique number that can be used to hash Color4 objects
  2049. */
  2050. Color4.prototype.getHashCode = function () {
  2051. var hash = this.r || 0;
  2052. hash = (hash * 397) ^ (this.g || 0);
  2053. hash = (hash * 397) ^ (this.b || 0);
  2054. hash = (hash * 397) ^ (this.a || 0);
  2055. return hash;
  2056. };
  2057. /**
  2058. * Creates a new Color4 copied from the current one
  2059. * @returns a new Color4 object
  2060. */
  2061. Color4.prototype.clone = function () {
  2062. return new Color4(this.r, this.g, this.b, this.a);
  2063. };
  2064. /**
  2065. * Copies the passed Color4 values into the current one
  2066. * @param source defines the source Color4 object
  2067. * @returns the current updated Color4 object
  2068. */
  2069. Color4.prototype.copyFrom = function (source) {
  2070. this.r = source.r;
  2071. this.g = source.g;
  2072. this.b = source.b;
  2073. this.a = source.a;
  2074. return this;
  2075. };
  2076. /**
  2077. * Copies the passed float values into the current one
  2078. * @param r defines the red component to read from
  2079. * @param g defines the green component to read from
  2080. * @param b defines the blue component to read from
  2081. * @param a defines the alpha component to read from
  2082. * @returns the current updated Color4 object
  2083. */
  2084. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2085. this.r = r;
  2086. this.g = g;
  2087. this.b = b;
  2088. this.a = a;
  2089. return this;
  2090. };
  2091. /**
  2092. * Copies the passed float values into the current one
  2093. * @param r defines the red component to read from
  2094. * @param g defines the green component to read from
  2095. * @param b defines the blue component to read from
  2096. * @param a defines the alpha component to read from
  2097. * @returns the current updated Color4 object
  2098. */
  2099. Color4.prototype.set = function (r, g, b, a) {
  2100. return this.copyFromFloats(r, g, b, a);
  2101. };
  2102. /**
  2103. * Compute the Color4 hexadecimal code as a string
  2104. * @returns a string containing the hexadecimal representation of the Color4 object
  2105. */
  2106. Color4.prototype.toHexString = function () {
  2107. var intR = (this.r * 255) | 0;
  2108. var intG = (this.g * 255) | 0;
  2109. var intB = (this.b * 255) | 0;
  2110. var intA = (this.a * 255) | 0;
  2111. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2112. };
  2113. /**
  2114. * Computes a new Color4 converted from the current one to linear space
  2115. * @returns a new Color4 object
  2116. */
  2117. Color4.prototype.toLinearSpace = function () {
  2118. var convertedColor = new Color4();
  2119. this.toLinearSpaceToRef(convertedColor);
  2120. return convertedColor;
  2121. };
  2122. /**
  2123. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2124. * @param convertedColor defines the Color4 object where to store the linear space version
  2125. * @returns the unmodified Color4
  2126. */
  2127. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2128. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2129. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2130. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2131. convertedColor.a = this.a;
  2132. return this;
  2133. };
  2134. /**
  2135. * Computes a new Color4 converted from the current one to gamma space
  2136. * @returns a new Color4 object
  2137. */
  2138. Color4.prototype.toGammaSpace = function () {
  2139. var convertedColor = new Color4();
  2140. this.toGammaSpaceToRef(convertedColor);
  2141. return convertedColor;
  2142. };
  2143. /**
  2144. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2145. * @param convertedColor defines the Color4 object where to store the gamma space version
  2146. * @returns the unmodified Color4
  2147. */
  2148. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2149. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2150. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2151. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2152. convertedColor.a = this.a;
  2153. return this;
  2154. };
  2155. // Statics
  2156. /**
  2157. * Creates a new Color4 from the string containing valid hexadecimal values
  2158. * @param hex defines a string containing valid hexadecimal values
  2159. * @returns a new Color4 object
  2160. */
  2161. Color4.FromHexString = function (hex) {
  2162. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2163. return new Color4(0.0, 0.0, 0.0, 0.0);
  2164. }
  2165. var r = parseInt(hex.substring(1, 3), 16);
  2166. var g = parseInt(hex.substring(3, 5), 16);
  2167. var b = parseInt(hex.substring(5, 7), 16);
  2168. var a = parseInt(hex.substring(7, 9), 16);
  2169. return Color4.FromInts(r, g, b, a);
  2170. };
  2171. /**
  2172. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2173. * @param left defines the start value
  2174. * @param right defines the end value
  2175. * @param amount defines the gradient factor
  2176. * @returns a new Color4 object
  2177. */
  2178. Color4.Lerp = function (left, right, amount) {
  2179. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2180. Color4.LerpToRef(left, right, amount, result);
  2181. return result;
  2182. };
  2183. /**
  2184. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2185. * @param left defines the start value
  2186. * @param right defines the end value
  2187. * @param amount defines the gradient factor
  2188. * @param result defines the Color4 object where to store data
  2189. */
  2190. Color4.LerpToRef = function (left, right, amount, result) {
  2191. result.r = left.r + (right.r - left.r) * amount;
  2192. result.g = left.g + (right.g - left.g) * amount;
  2193. result.b = left.b + (right.b - left.b) * amount;
  2194. result.a = left.a + (right.a - left.a) * amount;
  2195. };
  2196. /**
  2197. * Creates a new Color4 from the starting index element of the passed array
  2198. * @param array defines the source array to read from
  2199. * @param offset defines the offset in the source array
  2200. * @returns a new Color4 object
  2201. */
  2202. Color4.FromArray = function (array, offset) {
  2203. if (offset === void 0) { offset = 0; }
  2204. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2205. };
  2206. /**
  2207. * Creates a new Color3 from integer values (< 256)
  2208. * @param r defines the red component to read from (value between 0 and 255)
  2209. * @param g defines the green component to read from (value between 0 and 255)
  2210. * @param b defines the blue component to read from (value between 0 and 255)
  2211. * @param a defines the alpha component to read from (value between 0 and 255)
  2212. * @returns a new Color3 object
  2213. */
  2214. Color4.FromInts = function (r, g, b, a) {
  2215. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2216. };
  2217. /**
  2218. * Check the content of a given array and convert it to an array containing RGBA data
  2219. * If the original array was already containing count * 4 values then it is returned directly
  2220. * @param colors defines the array to check
  2221. * @param count defines the number of RGBA data to expect
  2222. * @returns an array containing count * 4 values (RGBA)
  2223. */
  2224. Color4.CheckColors4 = function (colors, count) {
  2225. // Check if color3 was used
  2226. if (colors.length === count * 3) {
  2227. var colors4 = [];
  2228. for (var index = 0; index < colors.length; index += 3) {
  2229. var newIndex = (index / 3) * 4;
  2230. colors4[newIndex] = colors[index];
  2231. colors4[newIndex + 1] = colors[index + 1];
  2232. colors4[newIndex + 2] = colors[index + 2];
  2233. colors4[newIndex + 3] = 1.0;
  2234. }
  2235. return colors4;
  2236. }
  2237. return colors;
  2238. };
  2239. return Color4;
  2240. }());
  2241. BABYLON.Color4 = Color4;
  2242. var Vector2 = /** @class */ (function () {
  2243. /**
  2244. * Creates a new Vector2 from the passed x and y coordinates.
  2245. */
  2246. function Vector2(x, y) {
  2247. this.x = x;
  2248. this.y = y;
  2249. }
  2250. /**
  2251. * Returns a string with the Vector2 coordinates.
  2252. */
  2253. Vector2.prototype.toString = function () {
  2254. return "{X: " + this.x + " Y:" + this.y + "}";
  2255. };
  2256. /**
  2257. * Returns the string "Vector2"
  2258. */
  2259. Vector2.prototype.getClassName = function () {
  2260. return "Vector2";
  2261. };
  2262. /**
  2263. * Returns the Vector2 hash code as a number.
  2264. */
  2265. Vector2.prototype.getHashCode = function () {
  2266. var hash = this.x || 0;
  2267. hash = (hash * 397) ^ (this.y || 0);
  2268. return hash;
  2269. };
  2270. // Operators
  2271. /**
  2272. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2273. * Returns the Vector2.
  2274. */
  2275. Vector2.prototype.toArray = function (array, index) {
  2276. if (index === void 0) { index = 0; }
  2277. array[index] = this.x;
  2278. array[index + 1] = this.y;
  2279. return this;
  2280. };
  2281. /**
  2282. * Returns a new array with 2 elements : the Vector2 coordinates.
  2283. */
  2284. Vector2.prototype.asArray = function () {
  2285. var result = new Array();
  2286. this.toArray(result, 0);
  2287. return result;
  2288. };
  2289. /**
  2290. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2291. * Returns the updated Vector2.
  2292. */
  2293. Vector2.prototype.copyFrom = function (source) {
  2294. this.x = source.x;
  2295. this.y = source.y;
  2296. return this;
  2297. };
  2298. /**
  2299. * Sets the Vector2 coordinates with the passed floats.
  2300. * Returns the updated Vector2.
  2301. */
  2302. Vector2.prototype.copyFromFloats = function (x, y) {
  2303. this.x = x;
  2304. this.y = y;
  2305. return this;
  2306. };
  2307. /**
  2308. * Sets the Vector2 coordinates with the passed floats.
  2309. * Returns the updated Vector2.
  2310. */
  2311. Vector2.prototype.set = function (x, y) {
  2312. return this.copyFromFloats(x, y);
  2313. };
  2314. /**
  2315. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2316. */
  2317. Vector2.prototype.add = function (otherVector) {
  2318. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2319. };
  2320. /**
  2321. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2322. * Returns the Vector2.
  2323. */
  2324. Vector2.prototype.addToRef = function (otherVector, result) {
  2325. result.x = this.x + otherVector.x;
  2326. result.y = this.y + otherVector.y;
  2327. return this;
  2328. };
  2329. /**
  2330. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2331. * Returns the updated Vector2.
  2332. */
  2333. Vector2.prototype.addInPlace = function (otherVector) {
  2334. this.x += otherVector.x;
  2335. this.y += otherVector.y;
  2336. return this;
  2337. };
  2338. /**
  2339. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2340. */
  2341. Vector2.prototype.addVector3 = function (otherVector) {
  2342. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2343. };
  2344. /**
  2345. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2346. */
  2347. Vector2.prototype.subtract = function (otherVector) {
  2348. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2349. };
  2350. /**
  2351. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2352. * Returns the Vector2.
  2353. */
  2354. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2355. result.x = this.x - otherVector.x;
  2356. result.y = this.y - otherVector.y;
  2357. return this;
  2358. };
  2359. /**
  2360. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2361. * Returns the updated Vector2.
  2362. */
  2363. Vector2.prototype.subtractInPlace = function (otherVector) {
  2364. this.x -= otherVector.x;
  2365. this.y -= otherVector.y;
  2366. return this;
  2367. };
  2368. /**
  2369. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2370. * Returns the updated Vector2.
  2371. */
  2372. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2373. this.x *= otherVector.x;
  2374. this.y *= otherVector.y;
  2375. return this;
  2376. };
  2377. /**
  2378. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2379. */
  2380. Vector2.prototype.multiply = function (otherVector) {
  2381. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2382. };
  2383. /**
  2384. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2385. * Returns the Vector2.
  2386. */
  2387. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2388. result.x = this.x * otherVector.x;
  2389. result.y = this.y * otherVector.y;
  2390. return this;
  2391. };
  2392. /**
  2393. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2394. */
  2395. Vector2.prototype.multiplyByFloats = function (x, y) {
  2396. return new Vector2(this.x * x, this.y * y);
  2397. };
  2398. /**
  2399. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2400. */
  2401. Vector2.prototype.divide = function (otherVector) {
  2402. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2403. };
  2404. /**
  2405. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2406. * Returns the 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 passed ones.
  2415. * Returns the updated Vector3.
  2416. */
  2417. Vector2.prototype.divideInPlace = function (otherVector) {
  2418. return this.divideToRef(otherVector, this);
  2419. };
  2420. /**
  2421. * Returns a new Vector2 with current Vector2 negated coordinates.
  2422. */
  2423. Vector2.prototype.negate = function () {
  2424. return new Vector2(-this.x, -this.y);
  2425. };
  2426. /**
  2427. * Multiply the Vector2 coordinates by scale.
  2428. * Returns the updated Vector2.
  2429. */
  2430. Vector2.prototype.scaleInPlace = function (scale) {
  2431. this.x *= scale;
  2432. this.y *= scale;
  2433. return this;
  2434. };
  2435. /**
  2436. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2437. */
  2438. Vector2.prototype.scale = function (scale) {
  2439. var result = new Vector2(0, 0);
  2440. this.scaleToRef(scale, result);
  2441. return result;
  2442. };
  2443. /**
  2444. * Scale the current Vector2 values by a factor to a given Vector2
  2445. * @param scale defines the scale factor
  2446. * @param result defines the Vector2 object where to store the result
  2447. * @returns the unmodified current Vector2
  2448. */
  2449. Vector2.prototype.scaleToRef = function (scale, result) {
  2450. result.x = this.x * scale;
  2451. result.y = this.y * scale;
  2452. return this;
  2453. };
  2454. /**
  2455. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2456. * @param scale defines the scale factor
  2457. * @param result defines the Vector2 object where to store the result
  2458. * @returns the unmodified current Vector2
  2459. */
  2460. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2461. result.x += this.x * scale;
  2462. result.y += this.y * scale;
  2463. return this;
  2464. };
  2465. /**
  2466. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2467. */
  2468. Vector2.prototype.equals = function (otherVector) {
  2469. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2470. };
  2471. /**
  2472. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2473. */
  2474. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2475. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2476. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2477. };
  2478. // Properties
  2479. /**
  2480. * Returns the vector length (float).
  2481. */
  2482. Vector2.prototype.length = function () {
  2483. return Math.sqrt(this.x * this.x + this.y * this.y);
  2484. };
  2485. /**
  2486. * Returns the vector squared length (float);
  2487. */
  2488. Vector2.prototype.lengthSquared = function () {
  2489. return (this.x * this.x + this.y * this.y);
  2490. };
  2491. // Methods
  2492. /**
  2493. * Normalize the vector.
  2494. * Returns the updated Vector2.
  2495. */
  2496. Vector2.prototype.normalize = function () {
  2497. var len = this.length();
  2498. if (len === 0)
  2499. return this;
  2500. var num = 1.0 / len;
  2501. this.x *= num;
  2502. this.y *= num;
  2503. return this;
  2504. };
  2505. /**
  2506. * Returns a new Vector2 copied from the Vector2.
  2507. */
  2508. Vector2.prototype.clone = function () {
  2509. return new Vector2(this.x, this.y);
  2510. };
  2511. // Statics
  2512. /**
  2513. * Returns a new Vector2(0, 0)
  2514. */
  2515. Vector2.Zero = function () {
  2516. return new Vector2(0, 0);
  2517. };
  2518. /**
  2519. * Returns a new Vector2(1, 1)
  2520. */
  2521. Vector2.One = function () {
  2522. return new Vector2(1, 1);
  2523. };
  2524. /**
  2525. * Returns a new Vector2 set from the passed index element of the passed array.
  2526. */
  2527. Vector2.FromArray = function (array, offset) {
  2528. if (offset === void 0) { offset = 0; }
  2529. return new Vector2(array[offset], array[offset + 1]);
  2530. };
  2531. /**
  2532. * Sets "result" from the passed index element of the passed array.
  2533. */
  2534. Vector2.FromArrayToRef = function (array, offset, result) {
  2535. result.x = array[offset];
  2536. result.y = array[offset + 1];
  2537. };
  2538. /**
  2539. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2540. */
  2541. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2542. var squared = amount * amount;
  2543. var cubed = amount * squared;
  2544. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2545. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2546. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2547. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2548. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2549. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2550. return new Vector2(x, y);
  2551. };
  2552. /**
  2553. * 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".
  2554. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2555. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2556. */
  2557. Vector2.Clamp = function (value, min, max) {
  2558. var x = value.x;
  2559. x = (x > max.x) ? max.x : x;
  2560. x = (x < min.x) ? min.x : x;
  2561. var y = value.y;
  2562. y = (y > max.y) ? max.y : y;
  2563. y = (y < min.y) ? min.y : y;
  2564. return new Vector2(x, y);
  2565. };
  2566. /**
  2567. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2568. */
  2569. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2570. var squared = amount * amount;
  2571. var cubed = amount * squared;
  2572. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2573. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2574. var part3 = (cubed - (2.0 * squared)) + amount;
  2575. var part4 = cubed - squared;
  2576. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2577. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2578. return new Vector2(x, y);
  2579. };
  2580. /**
  2581. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2582. */
  2583. Vector2.Lerp = function (start, end, amount) {
  2584. var x = start.x + ((end.x - start.x) * amount);
  2585. var y = start.y + ((end.y - start.y) * amount);
  2586. return new Vector2(x, y);
  2587. };
  2588. /**
  2589. * Returns the dot product (float) of the vector "left" and the vector "right".
  2590. */
  2591. Vector2.Dot = function (left, right) {
  2592. return left.x * right.x + left.y * right.y;
  2593. };
  2594. /**
  2595. * Returns a new Vector2 equal to the normalized passed vector.
  2596. */
  2597. Vector2.Normalize = function (vector) {
  2598. var newVector = vector.clone();
  2599. newVector.normalize();
  2600. return newVector;
  2601. };
  2602. /**
  2603. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2604. */
  2605. Vector2.Minimize = function (left, right) {
  2606. var x = (left.x < right.x) ? left.x : right.x;
  2607. var y = (left.y < right.y) ? left.y : right.y;
  2608. return new Vector2(x, y);
  2609. };
  2610. /**
  2611. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2612. */
  2613. Vector2.Maximize = function (left, right) {
  2614. var x = (left.x > right.x) ? left.x : right.x;
  2615. var y = (left.y > right.y) ? left.y : right.y;
  2616. return new Vector2(x, y);
  2617. };
  2618. /**
  2619. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2620. */
  2621. Vector2.Transform = function (vector, transformation) {
  2622. var r = Vector2.Zero();
  2623. Vector2.TransformToRef(vector, transformation, r);
  2624. return r;
  2625. };
  2626. /**
  2627. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2628. */
  2629. Vector2.TransformToRef = function (vector, transformation, result) {
  2630. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2631. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2632. result.x = x;
  2633. result.y = y;
  2634. };
  2635. /**
  2636. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2637. */
  2638. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2639. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2640. var sign = a < 0 ? -1 : 1;
  2641. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2642. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2643. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2644. };
  2645. /**
  2646. * Returns the distance (float) between the vectors "value1" and "value2".
  2647. */
  2648. Vector2.Distance = function (value1, value2) {
  2649. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2650. };
  2651. /**
  2652. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2653. */
  2654. Vector2.DistanceSquared = function (value1, value2) {
  2655. var x = value1.x - value2.x;
  2656. var y = value1.y - value2.y;
  2657. return (x * x) + (y * y);
  2658. };
  2659. /**
  2660. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2661. */
  2662. Vector2.Center = function (value1, value2) {
  2663. var center = value1.add(value2);
  2664. center.scaleInPlace(0.5);
  2665. return center;
  2666. };
  2667. /**
  2668. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2669. */
  2670. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2671. var l2 = Vector2.DistanceSquared(segA, segB);
  2672. if (l2 === 0.0) {
  2673. return Vector2.Distance(p, segA);
  2674. }
  2675. var v = segB.subtract(segA);
  2676. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2677. var proj = segA.add(v.multiplyByFloats(t, t));
  2678. return Vector2.Distance(p, proj);
  2679. };
  2680. return Vector2;
  2681. }());
  2682. BABYLON.Vector2 = Vector2;
  2683. /**
  2684. * Classed used to store (x,y,z) vector representation
  2685. * A Vector3 is the main object used in 3D geometry
  2686. * It can represent etiher the coordinates of a point the space, either a direction
  2687. * Reminder: Babylon.js uses a left handed forward facing system
  2688. */
  2689. var Vector3 = /** @class */ (function () {
  2690. /**
  2691. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2692. * @param x defines the first coordinates (on X axis)
  2693. * @param y defines the second coordinates (on Y axis)
  2694. * @param z defines the third coordinates (on Z axis)
  2695. */
  2696. function Vector3(
  2697. /**
  2698. * Defines the first coordinates (on X axis)
  2699. */
  2700. x,
  2701. /**
  2702. * Defines the second coordinates (on Y axis)
  2703. */
  2704. y,
  2705. /**
  2706. * Defines the third coordinates (on Z axis)
  2707. */
  2708. z) {
  2709. this.x = x;
  2710. this.y = y;
  2711. this.z = z;
  2712. }
  2713. /**
  2714. * Creates a string representation of the Vector3
  2715. * @returns a string with the Vector3 coordinates.
  2716. */
  2717. Vector3.prototype.toString = function () {
  2718. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2719. };
  2720. /**
  2721. * Gets the class name
  2722. * @returns the string "Vector3"
  2723. */
  2724. Vector3.prototype.getClassName = function () {
  2725. return "Vector3";
  2726. };
  2727. /**
  2728. * Creates the Vector3 hash code
  2729. * @returns a number which tends to be unique between Vector3 instances
  2730. */
  2731. Vector3.prototype.getHashCode = function () {
  2732. var hash = this.x || 0;
  2733. hash = (hash * 397) ^ (this.y || 0);
  2734. hash = (hash * 397) ^ (this.z || 0);
  2735. return hash;
  2736. };
  2737. // Operators
  2738. /**
  2739. * Creates an array containing three elements : the coordinates of the Vector3
  2740. * @returns a new array of numbers
  2741. */
  2742. Vector3.prototype.asArray = function () {
  2743. var result = [];
  2744. this.toArray(result, 0);
  2745. return result;
  2746. };
  2747. /**
  2748. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2749. * @param array defines the destination array
  2750. * @param index defines the offset in the destination array
  2751. * @returns the current Vector3
  2752. */
  2753. Vector3.prototype.toArray = function (array, index) {
  2754. if (index === void 0) { index = 0; }
  2755. array[index] = this.x;
  2756. array[index + 1] = this.y;
  2757. array[index + 2] = this.z;
  2758. return this;
  2759. };
  2760. /**
  2761. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2762. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2763. */
  2764. Vector3.prototype.toQuaternion = function () {
  2765. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2766. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2767. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2768. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2769. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2770. var cosy = Math.cos(this.y * 0.5);
  2771. var siny = Math.sin(this.y * 0.5);
  2772. result.x = coszMinusx * siny;
  2773. result.y = -sinzMinusx * siny;
  2774. result.z = sinxPlusz * cosy;
  2775. result.w = cosxPlusz * cosy;
  2776. return result;
  2777. };
  2778. /**
  2779. * Adds the passed vector to the current Vector3
  2780. * @param otherVector defines the second operand
  2781. * @returns the current updated Vector3
  2782. */
  2783. Vector3.prototype.addInPlace = function (otherVector) {
  2784. this.x += otherVector.x;
  2785. this.y += otherVector.y;
  2786. this.z += otherVector.z;
  2787. return this;
  2788. };
  2789. /**
  2790. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2791. * @param otherVector defines the second operand
  2792. * @returns the resulting Vector3
  2793. */
  2794. Vector3.prototype.add = function (otherVector) {
  2795. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2796. };
  2797. /**
  2798. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2799. * @param otherVector defines the second operand
  2800. * @param result defines the Vector3 object where to store the result
  2801. * @returns the current Vector3
  2802. */
  2803. Vector3.prototype.addToRef = function (otherVector, result) {
  2804. result.x = this.x + otherVector.x;
  2805. result.y = this.y + otherVector.y;
  2806. result.z = this.z + otherVector.z;
  2807. return this;
  2808. };
  2809. /**
  2810. * Subtract the passed vector from the current Vector3
  2811. * @param otherVector defines the second operand
  2812. * @returns the current updated Vector3
  2813. */
  2814. Vector3.prototype.subtractInPlace = function (otherVector) {
  2815. this.x -= otherVector.x;
  2816. this.y -= otherVector.y;
  2817. this.z -= otherVector.z;
  2818. return this;
  2819. };
  2820. /**
  2821. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2822. * @param otherVector defines the second operand
  2823. * @returns the resulting Vector3
  2824. */
  2825. Vector3.prototype.subtract = function (otherVector) {
  2826. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2827. };
  2828. /**
  2829. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2830. * @param otherVector defines the second operand
  2831. * @param result defines the Vector3 object where to store the result
  2832. * @returns the current Vector3
  2833. */
  2834. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2835. result.x = this.x - otherVector.x;
  2836. result.y = this.y - otherVector.y;
  2837. result.z = this.z - otherVector.z;
  2838. return this;
  2839. };
  2840. /**
  2841. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2842. * @param x defines the x coordinate of the operand
  2843. * @param y defines the y coordinate of the operand
  2844. * @param z defines the z coordinate of the operand
  2845. * @returns the resulting Vector3
  2846. */
  2847. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2848. return new Vector3(this.x - x, this.y - y, this.z - z);
  2849. };
  2850. /**
  2851. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2852. * @param x defines the x coordinate of the operand
  2853. * @param y defines the y coordinate of the operand
  2854. * @param z defines the z coordinate of the operand
  2855. * @param result defines the Vector3 object where to store the result
  2856. * @returns the current Vector3
  2857. */
  2858. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2859. result.x = this.x - x;
  2860. result.y = this.y - y;
  2861. result.z = this.z - z;
  2862. return this;
  2863. };
  2864. /**
  2865. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2866. * @returns a new Vector3
  2867. */
  2868. Vector3.prototype.negate = function () {
  2869. return new Vector3(-this.x, -this.y, -this.z);
  2870. };
  2871. /**
  2872. * Multiplies the Vector3 coordinates by the float "scale"
  2873. * @param scale defines the multiplier factor
  2874. * @returns the current updated Vector3
  2875. */
  2876. Vector3.prototype.scaleInPlace = function (scale) {
  2877. this.x *= scale;
  2878. this.y *= scale;
  2879. this.z *= scale;
  2880. return this;
  2881. };
  2882. /**
  2883. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2884. * @param scale defines the multiplier factor
  2885. * @returns a new Vector3
  2886. */
  2887. Vector3.prototype.scale = function (scale) {
  2888. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2889. };
  2890. /**
  2891. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2892. * @param scale defines the multiplier factor
  2893. * @param result defines the Vector3 object where to store the result
  2894. * @returns the current Vector3
  2895. */
  2896. Vector3.prototype.scaleToRef = function (scale, result) {
  2897. result.x = this.x * scale;
  2898. result.y = this.y * scale;
  2899. result.z = this.z * scale;
  2900. return this;
  2901. };
  2902. /**
  2903. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2904. * @param scale defines the scale factor
  2905. * @param result defines the Vector3 object where to store the result
  2906. * @returns the unmodified current Vector3
  2907. */
  2908. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2909. result.x += this.x * scale;
  2910. result.y += this.y * scale;
  2911. result.z += this.z * scale;
  2912. return this;
  2913. };
  2914. /**
  2915. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2916. * @param otherVector defines the second operand
  2917. * @returns true if both vectors are equals
  2918. */
  2919. Vector3.prototype.equals = function (otherVector) {
  2920. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2921. };
  2922. /**
  2923. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2924. * @param otherVector defines the second operand
  2925. * @param epsilon defines the minimal distance to define values as equals
  2926. * @returns true if both vectors are distant less than epsilon
  2927. */
  2928. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2929. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2930. 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);
  2931. };
  2932. /**
  2933. * Returns true if the current Vector3 coordinates equals the passed floats
  2934. * @param x defines the x coordinate of the operand
  2935. * @param y defines the y coordinate of the operand
  2936. * @param z defines the z coordinate of the operand
  2937. * @returns true if both vectors are equals
  2938. */
  2939. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2940. return this.x === x && this.y === y && this.z === z;
  2941. };
  2942. /**
  2943. * Multiplies the current Vector3 coordinates by the passed ones
  2944. * @param otherVector defines the second operand
  2945. * @returns the current updated Vector3
  2946. */
  2947. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2948. this.x *= otherVector.x;
  2949. this.y *= otherVector.y;
  2950. this.z *= otherVector.z;
  2951. return this;
  2952. };
  2953. /**
  2954. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2955. * @param otherVector defines the second operand
  2956. * @returns the new Vector3
  2957. */
  2958. Vector3.prototype.multiply = function (otherVector) {
  2959. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2960. };
  2961. /**
  2962. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2963. * @param otherVector defines the second operand
  2964. * @param result defines the Vector3 object where to store the result
  2965. * @returns the current Vector3
  2966. */
  2967. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2968. result.x = this.x * otherVector.x;
  2969. result.y = this.y * otherVector.y;
  2970. result.z = this.z * otherVector.z;
  2971. return this;
  2972. };
  2973. /**
  2974. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2975. * @param x defines the x coordinate of the operand
  2976. * @param y defines the y coordinate of the operand
  2977. * @param z defines the z coordinate of the operand
  2978. * @returns the new Vector3
  2979. */
  2980. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2981. return new Vector3(this.x * x, this.y * y, this.z * z);
  2982. };
  2983. /**
  2984. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2985. * @param otherVector defines the second operand
  2986. * @returns the new Vector3
  2987. */
  2988. Vector3.prototype.divide = function (otherVector) {
  2989. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2990. };
  2991. /**
  2992. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2993. * @param otherVector defines the second operand
  2994. * @param result defines the Vector3 object where to store the result
  2995. * @returns the current Vector3
  2996. */
  2997. Vector3.prototype.divideToRef = function (otherVector, result) {
  2998. result.x = this.x / otherVector.x;
  2999. result.y = this.y / otherVector.y;
  3000. result.z = this.z / otherVector.z;
  3001. return this;
  3002. };
  3003. /**
  3004. * Divides the current Vector3 coordinates by the passed ones.
  3005. * @param otherVector defines the second operand
  3006. * @returns the current updated Vector3
  3007. */
  3008. Vector3.prototype.divideInPlace = function (otherVector) {
  3009. return this.divideToRef(otherVector, this);
  3010. };
  3011. /**
  3012. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  3013. * @param other defines the second operand
  3014. * @returns the current updated Vector3
  3015. */
  3016. Vector3.prototype.minimizeInPlace = function (other) {
  3017. if (other.x < this.x)
  3018. this.x = other.x;
  3019. if (other.y < this.y)
  3020. this.y = other.y;
  3021. if (other.z < this.z)
  3022. this.z = other.z;
  3023. return this;
  3024. };
  3025. /**
  3026. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  3027. * @param other defines the second operand
  3028. * @returns the current updated Vector3
  3029. */
  3030. Vector3.prototype.maximizeInPlace = function (other) {
  3031. if (other.x > this.x)
  3032. this.x = other.x;
  3033. if (other.y > this.y)
  3034. this.y = other.y;
  3035. if (other.z > this.z)
  3036. this.z = other.z;
  3037. return this;
  3038. };
  3039. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3040. /**
  3041. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3042. */
  3043. get: function () {
  3044. var absX = Math.abs(this.x);
  3045. var absY = Math.abs(this.y);
  3046. if (absX !== absY) {
  3047. return true;
  3048. }
  3049. var absZ = Math.abs(this.z);
  3050. if (absX !== absZ) {
  3051. return true;
  3052. }
  3053. if (absY !== absZ) {
  3054. return true;
  3055. }
  3056. return false;
  3057. },
  3058. enumerable: true,
  3059. configurable: true
  3060. });
  3061. // Properties
  3062. /**
  3063. * Gets the length of the Vector3
  3064. * @returns the length of the Vecto3
  3065. */
  3066. Vector3.prototype.length = function () {
  3067. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3068. };
  3069. /**
  3070. * Gets the squared length of the Vector3
  3071. * @returns squared length of the Vector3
  3072. */
  3073. Vector3.prototype.lengthSquared = function () {
  3074. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3075. };
  3076. /**
  3077. * Normalize the current Vector3.
  3078. * Please note that this is an in place operation.
  3079. * @returns the current updated Vector3
  3080. */
  3081. Vector3.prototype.normalize = function () {
  3082. var len = this.length();
  3083. if (len === 0 || len === 1.0)
  3084. return this;
  3085. var num = 1.0 / len;
  3086. this.x *= num;
  3087. this.y *= num;
  3088. this.z *= num;
  3089. return this;
  3090. };
  3091. /**
  3092. * Normalize the current Vector3 to a new vector
  3093. * @returns the new Vector3
  3094. */
  3095. Vector3.prototype.normalizeToNew = function () {
  3096. var normalized = new Vector3(0, 0, 0);
  3097. this.normalizeToRef(normalized);
  3098. return normalized;
  3099. };
  3100. /**
  3101. * Normalize the current Vector3 to the reference
  3102. * @param reference define the Vector3 to update
  3103. * @returns the updated Vector3
  3104. */
  3105. Vector3.prototype.normalizeToRef = function (reference) {
  3106. var len = this.length();
  3107. if (len === 0 || len === 1.0) {
  3108. reference.set(this.x, this.y, this.z);
  3109. return reference;
  3110. }
  3111. var scale = 1.0 / len;
  3112. this.scaleToRef(scale, reference);
  3113. return reference;
  3114. };
  3115. /**
  3116. * Creates a new Vector3 copied from the current Vector3
  3117. * @returns the new Vector3
  3118. */
  3119. Vector3.prototype.clone = function () {
  3120. return new Vector3(this.x, this.y, this.z);
  3121. };
  3122. /**
  3123. * Copies the passed vector coordinates to the current Vector3 ones
  3124. * @param source defines the source Vector3
  3125. * @returns the current updated Vector3
  3126. */
  3127. Vector3.prototype.copyFrom = function (source) {
  3128. this.x = source.x;
  3129. this.y = source.y;
  3130. this.z = source.z;
  3131. return this;
  3132. };
  3133. /**
  3134. * Copies the passed floats to the current Vector3 coordinates
  3135. * @param x defines the x coordinate of the operand
  3136. * @param y defines the y coordinate of the operand
  3137. * @param z defines the z coordinate of the operand
  3138. * @returns the current updated Vector3
  3139. */
  3140. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3141. this.x = x;
  3142. this.y = y;
  3143. this.z = z;
  3144. return this;
  3145. };
  3146. /**
  3147. * Copies the passed floats to the current Vector3 coordinates
  3148. * @param x defines the x coordinate of the operand
  3149. * @param y defines the y coordinate of the operand
  3150. * @param z defines the z coordinate of the operand
  3151. * @returns the current updated Vector3
  3152. */
  3153. Vector3.prototype.set = function (x, y, z) {
  3154. return this.copyFromFloats(x, y, z);
  3155. };
  3156. // Statics
  3157. /**
  3158. * Get the clip factor between two vectors
  3159. * @param vector0 defines the first operand
  3160. * @param vector1 defines the second operand
  3161. * @param axis defines the axis to use
  3162. * @param size defines the size along the axis
  3163. * @returns the clip factor
  3164. */
  3165. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3166. var d0 = Vector3.Dot(vector0, axis) - size;
  3167. var d1 = Vector3.Dot(vector1, axis) - size;
  3168. var s = d0 / (d0 - d1);
  3169. return s;
  3170. };
  3171. /**
  3172. * Get angle between two vectors
  3173. * @param vector0 angle between vector0 and vector1
  3174. * @param vector1 angle between vector0 and vector1
  3175. * @param normal direction of the normal
  3176. * @return the angle between vector0 and vector1
  3177. */
  3178. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3179. var v0 = vector0.clone().normalize();
  3180. var v1 = vector1.clone().normalize();
  3181. var dot = Vector3.Dot(v0, v1);
  3182. var n = Vector3.Cross(v0, v1);
  3183. if (Vector3.Dot(n, normal) > 0) {
  3184. return Math.acos(dot);
  3185. }
  3186. return -Math.acos(dot);
  3187. };
  3188. /**
  3189. * Returns a new Vector3 set from the index "offset" of the passed array
  3190. * @param array defines the source array
  3191. * @param offset defines the offset in the source array
  3192. * @returns the new Vector3
  3193. */
  3194. Vector3.FromArray = function (array, offset) {
  3195. if (!offset) {
  3196. offset = 0;
  3197. }
  3198. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3199. };
  3200. /**
  3201. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3202. * This function is deprecated. Use FromArray instead
  3203. * @param array defines the source array
  3204. * @param offset defines the offset in the source array
  3205. * @returns the new Vector3
  3206. */
  3207. Vector3.FromFloatArray = function (array, offset) {
  3208. return Vector3.FromArray(array, offset);
  3209. };
  3210. /**
  3211. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3212. * @param array defines the source array
  3213. * @param offset defines the offset in the source array
  3214. * @param result defines the Vector3 where to store the result
  3215. */
  3216. Vector3.FromArrayToRef = function (array, offset, result) {
  3217. result.x = array[offset];
  3218. result.y = array[offset + 1];
  3219. result.z = array[offset + 2];
  3220. };
  3221. /**
  3222. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3223. * This function is deprecated. Use FromArrayToRef instead.
  3224. * @param array defines the source array
  3225. * @param offset defines the offset in the source array
  3226. * @param result defines the Vector3 where to store the result
  3227. */
  3228. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3229. return Vector3.FromArrayToRef(array, offset, result);
  3230. };
  3231. /**
  3232. * Sets the passed vector "result" with the passed floats.
  3233. * @param x defines the x coordinate of the source
  3234. * @param y defines the y coordinate of the source
  3235. * @param z defines the z coordinate of the source
  3236. * @param result defines the Vector3 where to store the result
  3237. */
  3238. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3239. result.x = x;
  3240. result.y = y;
  3241. result.z = z;
  3242. };
  3243. /**
  3244. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3245. * @returns a new empty Vector3
  3246. */
  3247. Vector3.Zero = function () {
  3248. return new Vector3(0.0, 0.0, 0.0);
  3249. };
  3250. /**
  3251. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3252. * @returns a new unit Vector3
  3253. */
  3254. Vector3.One = function () {
  3255. return new Vector3(1.0, 1.0, 1.0);
  3256. };
  3257. /**
  3258. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3259. * @returns a new up Vector3
  3260. */
  3261. Vector3.Up = function () {
  3262. return new Vector3(0.0, 1.0, 0.0);
  3263. };
  3264. /**
  3265. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3266. * @returns a new forward Vector3
  3267. */
  3268. Vector3.Forward = function () {
  3269. return new Vector3(0.0, 0.0, 1.0);
  3270. };
  3271. /**
  3272. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3273. * @returns a new right Vector3
  3274. */
  3275. Vector3.Right = function () {
  3276. return new Vector3(1.0, 0.0, 0.0);
  3277. };
  3278. /**
  3279. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3280. * @returns a new left Vector3
  3281. */
  3282. Vector3.Left = function () {
  3283. return new Vector3(-1.0, 0.0, 0.0);
  3284. };
  3285. /**
  3286. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3287. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3288. * @param vector defines the Vector3 to transform
  3289. * @param transformation defines the transformation matrix
  3290. * @returns the transformed Vector3
  3291. */
  3292. Vector3.TransformCoordinates = function (vector, transformation) {
  3293. var result = Vector3.Zero();
  3294. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3295. return result;
  3296. };
  3297. /**
  3298. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3299. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3300. * @param vector defines the Vector3 to transform
  3301. * @param transformation defines the transformation matrix
  3302. * @param result defines the Vector3 where to store the result
  3303. */
  3304. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3305. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3306. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3307. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3308. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3309. result.x = x / w;
  3310. result.y = y / w;
  3311. result.z = z / w;
  3312. };
  3313. /**
  3314. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3315. * This method computes tranformed coordinates only, not transformed direction vectors
  3316. * @param x define the x coordinate of the source vector
  3317. * @param y define the y coordinate of the source vector
  3318. * @param z define the z coordinate of the source vector
  3319. * @param transformation defines the transformation matrix
  3320. * @param result defines the Vector3 where to store the result
  3321. */
  3322. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3323. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3324. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3325. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3326. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3327. result.x = rx / rw;
  3328. result.y = ry / rw;
  3329. result.z = rz / rw;
  3330. };
  3331. /**
  3332. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3333. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3334. * @param vector defines the Vector3 to transform
  3335. * @param transformation defines the transformation matrix
  3336. * @returns the new Vector3
  3337. */
  3338. Vector3.TransformNormal = function (vector, transformation) {
  3339. var result = Vector3.Zero();
  3340. Vector3.TransformNormalToRef(vector, transformation, result);
  3341. return result;
  3342. };
  3343. /**
  3344. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3345. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3346. * @param vector defines the Vector3 to transform
  3347. * @param transformation defines the transformation matrix
  3348. * @param result defines the Vector3 where to store the result
  3349. */
  3350. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3351. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3352. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3353. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3354. result.x = x;
  3355. result.y = y;
  3356. result.z = z;
  3357. };
  3358. /**
  3359. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3360. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3361. * @param x define the x coordinate of the source vector
  3362. * @param y define the y coordinate of the source vector
  3363. * @param z define the z coordinate of the source vector
  3364. * @param transformation defines the transformation matrix
  3365. * @param result defines the Vector3 where to store the result
  3366. */
  3367. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3368. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3369. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3370. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3371. };
  3372. /**
  3373. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3374. * @param value1 defines the first control point
  3375. * @param value2 defines the second control point
  3376. * @param value3 defines the third control point
  3377. * @param value4 defines the fourth control point
  3378. * @param amount defines the amount on the spline to use
  3379. * @returns the new Vector3
  3380. */
  3381. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3382. var squared = amount * amount;
  3383. var cubed = amount * squared;
  3384. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3385. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3386. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3387. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3388. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3389. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3390. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3391. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3392. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3393. return new Vector3(x, y, z);
  3394. };
  3395. /**
  3396. * 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"
  3397. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3398. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3399. * @param value defines the current value
  3400. * @param min defines the lower range value
  3401. * @param max defines the upper range value
  3402. * @returns the new Vector3
  3403. */
  3404. Vector3.Clamp = function (value, min, max) {
  3405. var x = value.x;
  3406. x = (x > max.x) ? max.x : x;
  3407. x = (x < min.x) ? min.x : x;
  3408. var y = value.y;
  3409. y = (y > max.y) ? max.y : y;
  3410. y = (y < min.y) ? min.y : y;
  3411. var z = value.z;
  3412. z = (z > max.z) ? max.z : z;
  3413. z = (z < min.z) ? min.z : z;
  3414. return new Vector3(x, y, z);
  3415. };
  3416. /**
  3417. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3418. * @param value1 defines the first control point
  3419. * @param tangent1 defines the first tangent vector
  3420. * @param value2 defines the second control point
  3421. * @param tangent2 defines the second tangent vector
  3422. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3423. * @returns the new Vector3
  3424. */
  3425. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3426. var squared = amount * amount;
  3427. var cubed = amount * squared;
  3428. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3429. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3430. var part3 = (cubed - (2.0 * squared)) + amount;
  3431. var part4 = cubed - squared;
  3432. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3433. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3434. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3435. return new Vector3(x, y, z);
  3436. };
  3437. /**
  3438. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3439. * @param start defines the start value
  3440. * @param end defines the end value
  3441. * @param amount max defines amount between both (between 0 and 1)
  3442. * @returns the new Vector3
  3443. */
  3444. Vector3.Lerp = function (start, end, amount) {
  3445. var result = new Vector3(0, 0, 0);
  3446. Vector3.LerpToRef(start, end, amount, result);
  3447. return result;
  3448. };
  3449. /**
  3450. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3451. * @param start defines the start value
  3452. * @param end defines the end value
  3453. * @param amount max defines amount between both (between 0 and 1)
  3454. * @param result defines the Vector3 where to store the result
  3455. */
  3456. Vector3.LerpToRef = function (start, end, amount, result) {
  3457. result.x = start.x + ((end.x - start.x) * amount);
  3458. result.y = start.y + ((end.y - start.y) * amount);
  3459. result.z = start.z + ((end.z - start.z) * amount);
  3460. };
  3461. /**
  3462. * Returns the dot product (float) between the vectors "left" and "right"
  3463. * @param left defines the left operand
  3464. * @param right defines the right operand
  3465. * @returns the dot product
  3466. */
  3467. Vector3.Dot = function (left, right) {
  3468. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3469. };
  3470. /**
  3471. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3472. * The cross product is then orthogonal to both "left" and "right"
  3473. * @param left defines the left operand
  3474. * @param right defines the right operand
  3475. * @returns the cross product
  3476. */
  3477. Vector3.Cross = function (left, right) {
  3478. var result = Vector3.Zero();
  3479. Vector3.CrossToRef(left, right, result);
  3480. return result;
  3481. };
  3482. /**
  3483. * Sets the passed vector "result" with the cross product of "left" and "right"
  3484. * The cross product is then orthogonal to both "left" and "right"
  3485. * @param left defines the left operand
  3486. * @param right defines the right operand
  3487. * @param result defines the Vector3 where to store the result
  3488. */
  3489. Vector3.CrossToRef = function (left, right, result) {
  3490. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3491. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3492. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3493. result.copyFrom(MathTmp.Vector3[0]);
  3494. };
  3495. /**
  3496. * Returns a new Vector3 as the normalization of the passed vector
  3497. * @param vector defines the Vector3 to normalize
  3498. * @returns the new Vector3
  3499. */
  3500. Vector3.Normalize = function (vector) {
  3501. var result = Vector3.Zero();
  3502. Vector3.NormalizeToRef(vector, result);
  3503. return result;
  3504. };
  3505. /**
  3506. * Sets the passed vector "result" with the normalization of the passed first vector
  3507. * @param vector defines the Vector3 to normalize
  3508. * @param result defines the Vector3 where to store the result
  3509. */
  3510. Vector3.NormalizeToRef = function (vector, result) {
  3511. result.copyFrom(vector);
  3512. result.normalize();
  3513. };
  3514. /**
  3515. * Project a Vector3 onto screen space
  3516. * @param vector defines the Vector3 to project
  3517. * @param world defines the world matrix to use
  3518. * @param transform defines the transform (view x projection) matrix to use
  3519. * @param viewport defines the screen viewport to use
  3520. * @returns the new Vector3
  3521. */
  3522. Vector3.Project = function (vector, world, transform, viewport) {
  3523. var cw = viewport.width;
  3524. var ch = viewport.height;
  3525. var cx = viewport.x;
  3526. var cy = viewport.y;
  3527. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3528. 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);
  3529. var matrix = MathTmp.Matrix[0];
  3530. world.multiplyToRef(transform, matrix);
  3531. matrix.multiplyToRef(viewportMatrix, matrix);
  3532. return Vector3.TransformCoordinates(vector, matrix);
  3533. };
  3534. /**
  3535. * Unproject from screen space to object space
  3536. * @param source defines the screen space Vector3 to use
  3537. * @param viewportWidth defines the current width of the viewport
  3538. * @param viewportHeight defines the current height of the viewport
  3539. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3540. * @param transform defines the transform (view x projection) matrix to use
  3541. * @returns the new Vector3
  3542. */
  3543. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3544. var matrix = MathTmp.Matrix[0];
  3545. world.multiplyToRef(transform, matrix);
  3546. matrix.invert();
  3547. source.x = source.x / viewportWidth * 2 - 1;
  3548. source.y = -(source.y / viewportHeight * 2 - 1);
  3549. var vector = Vector3.TransformCoordinates(source, matrix);
  3550. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3551. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3552. vector = vector.scale(1.0 / num);
  3553. }
  3554. return vector;
  3555. };
  3556. /**
  3557. * Unproject from screen space to object space
  3558. * @param source defines the screen space Vector3 to use
  3559. * @param viewportWidth defines the current width of the viewport
  3560. * @param viewportHeight defines the current height of the viewport
  3561. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3562. * @param view defines the view matrix to use
  3563. * @param projection defines the projection matrix to use
  3564. * @returns the new Vector3
  3565. */
  3566. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3567. var result = Vector3.Zero();
  3568. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3569. return result;
  3570. };
  3571. /**
  3572. * Unproject from screen space to object space
  3573. * @param source defines the screen space Vector3 to use
  3574. * @param viewportWidth defines the current width of the viewport
  3575. * @param viewportHeight defines the current height of the viewport
  3576. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3577. * @param view defines the view matrix to use
  3578. * @param projection defines the projection matrix to use
  3579. * @param result defines the Vector3 where to store the result
  3580. */
  3581. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3582. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3583. };
  3584. /**
  3585. * Unproject from screen space to object space
  3586. * @param sourceX defines the screen space x coordinate to use
  3587. * @param sourceY defines the screen space y coordinate to use
  3588. * @param sourceZ defines the screen space z coordinate to use
  3589. * @param viewportWidth defines the current width of the viewport
  3590. * @param viewportHeight defines the current height of the viewport
  3591. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3592. * @param view defines the view matrix to use
  3593. * @param projection defines the projection matrix to use
  3594. * @param result defines the Vector3 where to store the result
  3595. */
  3596. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3597. var matrix = MathTmp.Matrix[0];
  3598. world.multiplyToRef(view, matrix);
  3599. matrix.multiplyToRef(projection, matrix);
  3600. matrix.invert();
  3601. var screenSource = MathTmp.Vector3[0];
  3602. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3603. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3604. screenSource.z = 2 * sourceZ - 1.0;
  3605. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3606. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3607. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3608. result.scaleInPlace(1.0 / num);
  3609. }
  3610. };
  3611. /**
  3612. * Gets the minimal coordinate values between two Vector3
  3613. * @param left defines the first operand
  3614. * @param right defines the second operand
  3615. * @returns the new Vector3
  3616. */
  3617. Vector3.Minimize = function (left, right) {
  3618. var min = left.clone();
  3619. min.minimizeInPlace(right);
  3620. return min;
  3621. };
  3622. /**
  3623. * Gets the maximal coordinate values between two Vector3
  3624. * @param left defines the first operand
  3625. * @param right defines the second operand
  3626. * @returns the new Vector3
  3627. */
  3628. Vector3.Maximize = function (left, right) {
  3629. var max = left.clone();
  3630. max.maximizeInPlace(right);
  3631. return max;
  3632. };
  3633. /**
  3634. * Returns the distance between the vectors "value1" and "value2"
  3635. * @param value1 defines the first operand
  3636. * @param value2 defines the second operand
  3637. * @returns the distance
  3638. */
  3639. Vector3.Distance = function (value1, value2) {
  3640. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3641. };
  3642. /**
  3643. * Returns the squared distance between the vectors "value1" and "value2"
  3644. * @param value1 defines the first operand
  3645. * @param value2 defines the second operand
  3646. * @returns the squared distance
  3647. */
  3648. Vector3.DistanceSquared = function (value1, value2) {
  3649. var x = value1.x - value2.x;
  3650. var y = value1.y - value2.y;
  3651. var z = value1.z - value2.z;
  3652. return (x * x) + (y * y) + (z * z);
  3653. };
  3654. /**
  3655. * Returns a new Vector3 located at the center between "value1" and "value2"
  3656. * @param value1 defines the first operand
  3657. * @param value2 defines the second operand
  3658. * @returns the new Vector3
  3659. */
  3660. Vector3.Center = function (value1, value2) {
  3661. var center = value1.add(value2);
  3662. center.scaleInPlace(0.5);
  3663. return center;
  3664. };
  3665. /**
  3666. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3667. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3668. * to something in order to rotate it from its local system to the given target system
  3669. * Note: axis1, axis2 and axis3 are normalized during this operation
  3670. * @param axis1 defines the first axis
  3671. * @param axis2 defines the second axis
  3672. * @param axis3 defines the third axis
  3673. * @returns a new Vector3
  3674. */
  3675. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3676. var rotation = Vector3.Zero();
  3677. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3678. return rotation;
  3679. };
  3680. /**
  3681. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3682. * @param axis1 defines the first axis
  3683. * @param axis2 defines the second axis
  3684. * @param axis3 defines the third axis
  3685. * @param ref defines the Vector3 where to store the result
  3686. */
  3687. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3688. var quat = MathTmp.Quaternion[0];
  3689. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3690. quat.toEulerAnglesToRef(ref);
  3691. };
  3692. return Vector3;
  3693. }());
  3694. BABYLON.Vector3 = Vector3;
  3695. //Vector4 class created for EulerAngle class conversion to Quaternion
  3696. var Vector4 = /** @class */ (function () {
  3697. /**
  3698. * Creates a Vector4 object from the passed floats.
  3699. */
  3700. function Vector4(x, y, z, w) {
  3701. this.x = x;
  3702. this.y = y;
  3703. this.z = z;
  3704. this.w = w;
  3705. }
  3706. /**
  3707. * Returns the string with the Vector4 coordinates.
  3708. */
  3709. Vector4.prototype.toString = function () {
  3710. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3711. };
  3712. /**
  3713. * Returns the string "Vector4".
  3714. */
  3715. Vector4.prototype.getClassName = function () {
  3716. return "Vector4";
  3717. };
  3718. /**
  3719. * Returns the Vector4 hash code.
  3720. */
  3721. Vector4.prototype.getHashCode = function () {
  3722. var hash = this.x || 0;
  3723. hash = (hash * 397) ^ (this.y || 0);
  3724. hash = (hash * 397) ^ (this.z || 0);
  3725. hash = (hash * 397) ^ (this.w || 0);
  3726. return hash;
  3727. };
  3728. // Operators
  3729. /**
  3730. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3731. */
  3732. Vector4.prototype.asArray = function () {
  3733. var result = new Array();
  3734. this.toArray(result, 0);
  3735. return result;
  3736. };
  3737. /**
  3738. * Populates the passed array from the passed index with the Vector4 coordinates.
  3739. * Returns the Vector4.
  3740. */
  3741. Vector4.prototype.toArray = function (array, index) {
  3742. if (index === undefined) {
  3743. index = 0;
  3744. }
  3745. array[index] = this.x;
  3746. array[index + 1] = this.y;
  3747. array[index + 2] = this.z;
  3748. array[index + 3] = this.w;
  3749. return this;
  3750. };
  3751. /**
  3752. * Adds the passed vector to the current Vector4.
  3753. * Returns the updated Vector4.
  3754. */
  3755. Vector4.prototype.addInPlace = function (otherVector) {
  3756. this.x += otherVector.x;
  3757. this.y += otherVector.y;
  3758. this.z += otherVector.z;
  3759. this.w += otherVector.w;
  3760. return this;
  3761. };
  3762. /**
  3763. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3764. */
  3765. Vector4.prototype.add = function (otherVector) {
  3766. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3767. };
  3768. /**
  3769. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3770. * Returns the current Vector4.
  3771. */
  3772. Vector4.prototype.addToRef = function (otherVector, result) {
  3773. result.x = this.x + otherVector.x;
  3774. result.y = this.y + otherVector.y;
  3775. result.z = this.z + otherVector.z;
  3776. result.w = this.w + otherVector.w;
  3777. return this;
  3778. };
  3779. /**
  3780. * Subtract in place the passed vector from the current Vector4.
  3781. * Returns the updated Vector4.
  3782. */
  3783. Vector4.prototype.subtractInPlace = function (otherVector) {
  3784. this.x -= otherVector.x;
  3785. this.y -= otherVector.y;
  3786. this.z -= otherVector.z;
  3787. this.w -= otherVector.w;
  3788. return this;
  3789. };
  3790. /**
  3791. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3792. */
  3793. Vector4.prototype.subtract = function (otherVector) {
  3794. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3795. };
  3796. /**
  3797. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3798. * Returns the current Vector4.
  3799. */
  3800. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3801. result.x = this.x - otherVector.x;
  3802. result.y = this.y - otherVector.y;
  3803. result.z = this.z - otherVector.z;
  3804. result.w = this.w - otherVector.w;
  3805. return this;
  3806. };
  3807. /**
  3808. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3809. */
  3810. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3811. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3812. };
  3813. /**
  3814. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3815. * Returns the current Vector4.
  3816. */
  3817. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3818. result.x = this.x - x;
  3819. result.y = this.y - y;
  3820. result.z = this.z - z;
  3821. result.w = this.w - w;
  3822. return this;
  3823. };
  3824. /**
  3825. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3826. */
  3827. Vector4.prototype.negate = function () {
  3828. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3829. };
  3830. /**
  3831. * Multiplies the current Vector4 coordinates by scale (float).
  3832. * Returns the updated Vector4.
  3833. */
  3834. Vector4.prototype.scaleInPlace = function (scale) {
  3835. this.x *= scale;
  3836. this.y *= scale;
  3837. this.z *= scale;
  3838. this.w *= scale;
  3839. return this;
  3840. };
  3841. /**
  3842. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3843. */
  3844. Vector4.prototype.scale = function (scale) {
  3845. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3846. };
  3847. /**
  3848. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3849. * Returns the current Vector4.
  3850. */
  3851. Vector4.prototype.scaleToRef = function (scale, result) {
  3852. result.x = this.x * scale;
  3853. result.y = this.y * scale;
  3854. result.z = this.z * scale;
  3855. result.w = this.w * scale;
  3856. return this;
  3857. };
  3858. /**
  3859. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3860. * @param scale defines the scale factor
  3861. * @param result defines the Vector4 object where to store the result
  3862. * @returns the unmodified current Vector4
  3863. */
  3864. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3865. result.x += this.x * scale;
  3866. result.y += this.y * scale;
  3867. result.z += this.z * scale;
  3868. result.w += this.w * scale;
  3869. return this;
  3870. };
  3871. /**
  3872. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3873. */
  3874. Vector4.prototype.equals = function (otherVector) {
  3875. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3876. };
  3877. /**
  3878. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3879. */
  3880. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3881. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3882. return otherVector
  3883. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3884. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3885. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3886. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3887. };
  3888. /**
  3889. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3890. */
  3891. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3892. return this.x === x && this.y === y && this.z === z && this.w === w;
  3893. };
  3894. /**
  3895. * Multiplies in place the current Vector4 by the passed one.
  3896. * Returns the updated Vector4.
  3897. */
  3898. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3899. this.x *= otherVector.x;
  3900. this.y *= otherVector.y;
  3901. this.z *= otherVector.z;
  3902. this.w *= otherVector.w;
  3903. return this;
  3904. };
  3905. /**
  3906. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3907. */
  3908. Vector4.prototype.multiply = function (otherVector) {
  3909. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3910. };
  3911. /**
  3912. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3913. * Returns the current Vector4.
  3914. */
  3915. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3916. result.x = this.x * otherVector.x;
  3917. result.y = this.y * otherVector.y;
  3918. result.z = this.z * otherVector.z;
  3919. result.w = this.w * otherVector.w;
  3920. return this;
  3921. };
  3922. /**
  3923. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3924. */
  3925. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3926. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3927. };
  3928. /**
  3929. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3930. */
  3931. Vector4.prototype.divide = function (otherVector) {
  3932. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3933. };
  3934. /**
  3935. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3936. * Returns the current Vector4.
  3937. */
  3938. Vector4.prototype.divideToRef = function (otherVector, result) {
  3939. result.x = this.x / otherVector.x;
  3940. result.y = this.y / otherVector.y;
  3941. result.z = this.z / otherVector.z;
  3942. result.w = this.w / otherVector.w;
  3943. return this;
  3944. };
  3945. /**
  3946. * Divides the current Vector3 coordinates by the passed ones.
  3947. * @returns the updated Vector3.
  3948. */
  3949. Vector4.prototype.divideInPlace = function (otherVector) {
  3950. return this.divideToRef(otherVector, this);
  3951. };
  3952. /**
  3953. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3954. * @param other defines the second operand
  3955. * @returns the current updated Vector4
  3956. */
  3957. Vector4.prototype.minimizeInPlace = function (other) {
  3958. if (other.x < this.x)
  3959. this.x = other.x;
  3960. if (other.y < this.y)
  3961. this.y = other.y;
  3962. if (other.z < this.z)
  3963. this.z = other.z;
  3964. if (other.w < this.w)
  3965. this.w = other.w;
  3966. return this;
  3967. };
  3968. /**
  3969. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3970. * @param other defines the second operand
  3971. * @returns the current updated Vector4
  3972. */
  3973. Vector4.prototype.maximizeInPlace = function (other) {
  3974. if (other.x > this.x)
  3975. this.x = other.x;
  3976. if (other.y > this.y)
  3977. this.y = other.y;
  3978. if (other.z > this.z)
  3979. this.z = other.z;
  3980. if (other.w > this.w)
  3981. this.w = other.w;
  3982. return this;
  3983. };
  3984. // Properties
  3985. /**
  3986. * Returns the Vector4 length (float).
  3987. */
  3988. Vector4.prototype.length = function () {
  3989. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3990. };
  3991. /**
  3992. * Returns the Vector4 squared length (float).
  3993. */
  3994. Vector4.prototype.lengthSquared = function () {
  3995. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3996. };
  3997. // Methods
  3998. /**
  3999. * Normalizes in place the Vector4.
  4000. * Returns the updated Vector4.
  4001. */
  4002. Vector4.prototype.normalize = function () {
  4003. var len = this.length();
  4004. if (len === 0)
  4005. return this;
  4006. var num = 1.0 / len;
  4007. this.x *= num;
  4008. this.y *= num;
  4009. this.z *= num;
  4010. this.w *= num;
  4011. return this;
  4012. };
  4013. /**
  4014. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4015. */
  4016. Vector4.prototype.toVector3 = function () {
  4017. return new Vector3(this.x, this.y, this.z);
  4018. };
  4019. /**
  4020. * Returns a new Vector4 copied from the current one.
  4021. */
  4022. Vector4.prototype.clone = function () {
  4023. return new Vector4(this.x, this.y, this.z, this.w);
  4024. };
  4025. /**
  4026. * Updates the current Vector4 with the passed one coordinates.
  4027. * Returns the updated Vector4.
  4028. */
  4029. Vector4.prototype.copyFrom = function (source) {
  4030. this.x = source.x;
  4031. this.y = source.y;
  4032. this.z = source.z;
  4033. this.w = source.w;
  4034. return this;
  4035. };
  4036. /**
  4037. * Updates the current Vector4 coordinates with the passed floats.
  4038. * Returns the updated Vector4.
  4039. */
  4040. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4041. this.x = x;
  4042. this.y = y;
  4043. this.z = z;
  4044. this.w = w;
  4045. return this;
  4046. };
  4047. /**
  4048. * Updates the current Vector4 coordinates with the passed floats.
  4049. * Returns the updated Vector4.
  4050. */
  4051. Vector4.prototype.set = function (x, y, z, w) {
  4052. return this.copyFromFloats(x, y, z, w);
  4053. };
  4054. // Statics
  4055. /**
  4056. * Returns a new Vector4 set from the starting index of the passed array.
  4057. */
  4058. Vector4.FromArray = function (array, offset) {
  4059. if (!offset) {
  4060. offset = 0;
  4061. }
  4062. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4063. };
  4064. /**
  4065. * Updates the passed vector "result" from the starting index of the passed array.
  4066. */
  4067. Vector4.FromArrayToRef = function (array, offset, result) {
  4068. result.x = array[offset];
  4069. result.y = array[offset + 1];
  4070. result.z = array[offset + 2];
  4071. result.w = array[offset + 3];
  4072. };
  4073. /**
  4074. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4075. */
  4076. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4077. Vector4.FromArrayToRef(array, offset, result);
  4078. };
  4079. /**
  4080. * Updates the passed vector "result" coordinates from the passed floats.
  4081. */
  4082. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4083. result.x = x;
  4084. result.y = y;
  4085. result.z = z;
  4086. result.w = w;
  4087. };
  4088. /**
  4089. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4090. */
  4091. Vector4.Zero = function () {
  4092. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4093. };
  4094. /**
  4095. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4096. */
  4097. Vector4.One = function () {
  4098. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4099. };
  4100. /**
  4101. * Returns a new normalized Vector4 from the passed one.
  4102. */
  4103. Vector4.Normalize = function (vector) {
  4104. var result = Vector4.Zero();
  4105. Vector4.NormalizeToRef(vector, result);
  4106. return result;
  4107. };
  4108. /**
  4109. * Updates the passed vector "result" from the normalization of the passed one.
  4110. */
  4111. Vector4.NormalizeToRef = function (vector, result) {
  4112. result.copyFrom(vector);
  4113. result.normalize();
  4114. };
  4115. Vector4.Minimize = function (left, right) {
  4116. var min = left.clone();
  4117. min.minimizeInPlace(right);
  4118. return min;
  4119. };
  4120. Vector4.Maximize = function (left, right) {
  4121. var max = left.clone();
  4122. max.maximizeInPlace(right);
  4123. return max;
  4124. };
  4125. /**
  4126. * Returns the distance (float) between the vectors "value1" and "value2".
  4127. */
  4128. Vector4.Distance = function (value1, value2) {
  4129. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4130. };
  4131. /**
  4132. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4133. */
  4134. Vector4.DistanceSquared = function (value1, value2) {
  4135. var x = value1.x - value2.x;
  4136. var y = value1.y - value2.y;
  4137. var z = value1.z - value2.z;
  4138. var w = value1.w - value2.w;
  4139. return (x * x) + (y * y) + (z * z) + (w * w);
  4140. };
  4141. /**
  4142. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4143. */
  4144. Vector4.Center = function (value1, value2) {
  4145. var center = value1.add(value2);
  4146. center.scaleInPlace(0.5);
  4147. return center;
  4148. };
  4149. /**
  4150. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4151. * This methods computes transformed normalized direction vectors only.
  4152. */
  4153. Vector4.TransformNormal = function (vector, transformation) {
  4154. var result = Vector4.Zero();
  4155. Vector4.TransformNormalToRef(vector, transformation, result);
  4156. return result;
  4157. };
  4158. /**
  4159. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4160. * This methods computes transformed normalized direction vectors only.
  4161. */
  4162. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4163. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4164. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4165. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4166. result.x = x;
  4167. result.y = y;
  4168. result.z = z;
  4169. result.w = vector.w;
  4170. };
  4171. /**
  4172. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4173. * This methods computes transformed normalized direction vectors only.
  4174. */
  4175. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4176. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4177. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4178. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4179. result.w = w;
  4180. };
  4181. return Vector4;
  4182. }());
  4183. BABYLON.Vector4 = Vector4;
  4184. var Size = /** @class */ (function () {
  4185. /**
  4186. * Creates a Size object from the passed width and height (floats).
  4187. */
  4188. function Size(width, height) {
  4189. this.width = width;
  4190. this.height = height;
  4191. }
  4192. // Returns a string with the Size width and height.
  4193. Size.prototype.toString = function () {
  4194. return "{W: " + this.width + ", H: " + this.height + "}";
  4195. };
  4196. /**
  4197. * Returns the string "Size"
  4198. */
  4199. Size.prototype.getClassName = function () {
  4200. return "Size";
  4201. };
  4202. /**
  4203. * Returns the Size hash code.
  4204. */
  4205. Size.prototype.getHashCode = function () {
  4206. var hash = this.width || 0;
  4207. hash = (hash * 397) ^ (this.height || 0);
  4208. return hash;
  4209. };
  4210. /**
  4211. * Updates the current size from the passed one.
  4212. * Returns the updated Size.
  4213. */
  4214. Size.prototype.copyFrom = function (src) {
  4215. this.width = src.width;
  4216. this.height = src.height;
  4217. };
  4218. /**
  4219. * Updates in place the current Size from the passed floats.
  4220. * Returns the updated Size.
  4221. */
  4222. Size.prototype.copyFromFloats = function (width, height) {
  4223. this.width = width;
  4224. this.height = height;
  4225. return this;
  4226. };
  4227. /**
  4228. * Updates in place the current Size from the passed floats.
  4229. * Returns the updated Size.
  4230. */
  4231. Size.prototype.set = function (width, height) {
  4232. return this.copyFromFloats(width, height);
  4233. };
  4234. /**
  4235. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4236. */
  4237. Size.prototype.multiplyByFloats = function (w, h) {
  4238. return new Size(this.width * w, this.height * h);
  4239. };
  4240. /**
  4241. * Returns a new Size copied from the passed one.
  4242. */
  4243. Size.prototype.clone = function () {
  4244. return new Size(this.width, this.height);
  4245. };
  4246. /**
  4247. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4248. */
  4249. Size.prototype.equals = function (other) {
  4250. if (!other) {
  4251. return false;
  4252. }
  4253. return (this.width === other.width) && (this.height === other.height);
  4254. };
  4255. Object.defineProperty(Size.prototype, "surface", {
  4256. /**
  4257. * Returns the surface of the Size : width * height (float).
  4258. */
  4259. get: function () {
  4260. return this.width * this.height;
  4261. },
  4262. enumerable: true,
  4263. configurable: true
  4264. });
  4265. /**
  4266. * Returns a new Size set to (0.0, 0.0)
  4267. */
  4268. Size.Zero = function () {
  4269. return new Size(0.0, 0.0);
  4270. };
  4271. /**
  4272. * Returns a new Size set as the addition result of the current Size and the passed one.
  4273. */
  4274. Size.prototype.add = function (otherSize) {
  4275. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4276. return r;
  4277. };
  4278. /**
  4279. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4280. */
  4281. Size.prototype.subtract = function (otherSize) {
  4282. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4283. return r;
  4284. };
  4285. /**
  4286. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4287. */
  4288. Size.Lerp = function (start, end, amount) {
  4289. var w = start.width + ((end.width - start.width) * amount);
  4290. var h = start.height + ((end.height - start.height) * amount);
  4291. return new Size(w, h);
  4292. };
  4293. return Size;
  4294. }());
  4295. BABYLON.Size = Size;
  4296. var Quaternion = /** @class */ (function () {
  4297. /**
  4298. * Creates a new Quaternion from the passed floats.
  4299. */
  4300. function Quaternion(x, y, z, w) {
  4301. if (x === void 0) { x = 0.0; }
  4302. if (y === void 0) { y = 0.0; }
  4303. if (z === void 0) { z = 0.0; }
  4304. if (w === void 0) { w = 1.0; }
  4305. this.x = x;
  4306. this.y = y;
  4307. this.z = z;
  4308. this.w = w;
  4309. }
  4310. /**
  4311. * Returns a string with the Quaternion coordinates.
  4312. */
  4313. Quaternion.prototype.toString = function () {
  4314. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4315. };
  4316. /**
  4317. * Returns the string "Quaternion".
  4318. */
  4319. Quaternion.prototype.getClassName = function () {
  4320. return "Quaternion";
  4321. };
  4322. /**
  4323. * Returns the Quaternion hash code.
  4324. */
  4325. Quaternion.prototype.getHashCode = function () {
  4326. var hash = this.x || 0;
  4327. hash = (hash * 397) ^ (this.y || 0);
  4328. hash = (hash * 397) ^ (this.z || 0);
  4329. hash = (hash * 397) ^ (this.w || 0);
  4330. return hash;
  4331. };
  4332. /**
  4333. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4334. */
  4335. Quaternion.prototype.asArray = function () {
  4336. return [this.x, this.y, this.z, this.w];
  4337. };
  4338. /**
  4339. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4340. */
  4341. Quaternion.prototype.equals = function (otherQuaternion) {
  4342. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4343. };
  4344. /**
  4345. * Returns a new Quaternion copied from the current one.
  4346. */
  4347. Quaternion.prototype.clone = function () {
  4348. return new Quaternion(this.x, this.y, this.z, this.w);
  4349. };
  4350. /**
  4351. * Updates the current Quaternion from the passed one coordinates.
  4352. * Returns the updated Quaterion.
  4353. */
  4354. Quaternion.prototype.copyFrom = function (other) {
  4355. this.x = other.x;
  4356. this.y = other.y;
  4357. this.z = other.z;
  4358. this.w = other.w;
  4359. return this;
  4360. };
  4361. /**
  4362. * Updates the current Quaternion from the passed float coordinates.
  4363. * Returns the updated Quaterion.
  4364. */
  4365. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4366. this.x = x;
  4367. this.y = y;
  4368. this.z = z;
  4369. this.w = w;
  4370. return this;
  4371. };
  4372. /**
  4373. * Updates the current Quaternion from the passed float coordinates.
  4374. * Returns the updated Quaterion.
  4375. */
  4376. Quaternion.prototype.set = function (x, y, z, w) {
  4377. return this.copyFromFloats(x, y, z, w);
  4378. };
  4379. /**
  4380. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4381. */
  4382. Quaternion.prototype.add = function (other) {
  4383. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4384. };
  4385. /**
  4386. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4387. */
  4388. Quaternion.prototype.subtract = function (other) {
  4389. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4390. };
  4391. /**
  4392. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4393. */
  4394. Quaternion.prototype.scale = function (value) {
  4395. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4396. };
  4397. /**
  4398. * Scale the current Quaternion values by a factor to a given Quaternion
  4399. * @param scale defines the scale factor
  4400. * @param result defines the Quaternion object where to store the result
  4401. * @returns the unmodified current Quaternion
  4402. */
  4403. Quaternion.prototype.scaleToRef = function (scale, result) {
  4404. result.x = this.x * scale;
  4405. result.y = this.y * scale;
  4406. result.z = this.z * scale;
  4407. result.w = this.w * scale;
  4408. return this;
  4409. };
  4410. /**
  4411. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4412. * @param scale defines the scale factor
  4413. * @param result defines the Quaternion object where to store the result
  4414. * @returns the unmodified current Quaternion
  4415. */
  4416. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4417. result.x += this.x * scale;
  4418. result.y += this.y * scale;
  4419. result.z += this.z * scale;
  4420. result.w += this.w * scale;
  4421. return this;
  4422. };
  4423. /**
  4424. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4425. */
  4426. Quaternion.prototype.multiply = function (q1) {
  4427. var result = new Quaternion(0, 0, 0, 1.0);
  4428. this.multiplyToRef(q1, result);
  4429. return result;
  4430. };
  4431. /**
  4432. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4433. * Returns the current Quaternion.
  4434. */
  4435. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4436. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4437. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4438. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4439. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4440. result.copyFromFloats(x, y, z, w);
  4441. return this;
  4442. };
  4443. /**
  4444. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4445. * Returns the updated Quaternion.
  4446. */
  4447. Quaternion.prototype.multiplyInPlace = function (q1) {
  4448. this.multiplyToRef(q1, this);
  4449. return this;
  4450. };
  4451. /**
  4452. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4453. * Returns the current Quaternion.
  4454. */
  4455. Quaternion.prototype.conjugateToRef = function (ref) {
  4456. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4457. return this;
  4458. };
  4459. /**
  4460. * Conjugates in place the current Quaternion.
  4461. * Returns the updated Quaternion.
  4462. */
  4463. Quaternion.prototype.conjugateInPlace = function () {
  4464. this.x *= -1;
  4465. this.y *= -1;
  4466. this.z *= -1;
  4467. return this;
  4468. };
  4469. /**
  4470. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4471. */
  4472. Quaternion.prototype.conjugate = function () {
  4473. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4474. return result;
  4475. };
  4476. /**
  4477. * Returns the Quaternion length (float).
  4478. */
  4479. Quaternion.prototype.length = function () {
  4480. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4481. };
  4482. /**
  4483. * Normalize in place the current Quaternion.
  4484. * Returns the updated Quaternion.
  4485. */
  4486. Quaternion.prototype.normalize = function () {
  4487. var length = 1.0 / this.length();
  4488. this.x *= length;
  4489. this.y *= length;
  4490. this.z *= length;
  4491. this.w *= length;
  4492. return this;
  4493. };
  4494. /**
  4495. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4496. * @param order is a reserved parameter and is ignore for now
  4497. * @returns the new Vector3
  4498. */
  4499. Quaternion.prototype.toEulerAngles = function (order) {
  4500. if (order === void 0) { order = "YZX"; }
  4501. var result = Vector3.Zero();
  4502. this.toEulerAnglesToRef(result, order);
  4503. return result;
  4504. };
  4505. /**
  4506. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4507. * @param result defines the vector which will be filled with the Euler angles
  4508. * @param order is a reserved parameter and is ignore for now
  4509. * @returns the current Quaternion
  4510. */
  4511. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4512. if (order === void 0) { order = "YZX"; }
  4513. var qz = this.z;
  4514. var qx = this.x;
  4515. var qy = this.y;
  4516. var qw = this.w;
  4517. var sqw = qw * qw;
  4518. var sqz = qz * qz;
  4519. var sqx = qx * qx;
  4520. var sqy = qy * qy;
  4521. var zAxisY = qy * qz - qx * qw;
  4522. var limit = .4999999;
  4523. if (zAxisY < -limit) {
  4524. result.y = 2 * Math.atan2(qy, qw);
  4525. result.x = Math.PI / 2;
  4526. result.z = 0;
  4527. }
  4528. else if (zAxisY > limit) {
  4529. result.y = 2 * Math.atan2(qy, qw);
  4530. result.x = -Math.PI / 2;
  4531. result.z = 0;
  4532. }
  4533. else {
  4534. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4535. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4536. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4537. }
  4538. return this;
  4539. };
  4540. /**
  4541. * Updates the passed rotation matrix with the current Quaternion values.
  4542. * Returns the current Quaternion.
  4543. */
  4544. Quaternion.prototype.toRotationMatrix = function (result) {
  4545. var xx = this.x * this.x;
  4546. var yy = this.y * this.y;
  4547. var zz = this.z * this.z;
  4548. var xy = this.x * this.y;
  4549. var zw = this.z * this.w;
  4550. var zx = this.z * this.x;
  4551. var yw = this.y * this.w;
  4552. var yz = this.y * this.z;
  4553. var xw = this.x * this.w;
  4554. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4555. result.m[1] = 2.0 * (xy + zw);
  4556. result.m[2] = 2.0 * (zx - yw);
  4557. result.m[3] = 0;
  4558. result.m[4] = 2.0 * (xy - zw);
  4559. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4560. result.m[6] = 2.0 * (yz + xw);
  4561. result.m[7] = 0;
  4562. result.m[8] = 2.0 * (zx + yw);
  4563. result.m[9] = 2.0 * (yz - xw);
  4564. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4565. result.m[11] = 0;
  4566. result.m[12] = 0;
  4567. result.m[13] = 0;
  4568. result.m[14] = 0;
  4569. result.m[15] = 1.0;
  4570. result._markAsUpdated();
  4571. return this;
  4572. };
  4573. /**
  4574. * Updates the current Quaternion from the passed rotation matrix values.
  4575. * Returns the updated Quaternion.
  4576. */
  4577. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4578. Quaternion.FromRotationMatrixToRef(matrix, this);
  4579. return this;
  4580. };
  4581. // Statics
  4582. /**
  4583. * Returns a new Quaternion set from the passed rotation matrix values.
  4584. */
  4585. Quaternion.FromRotationMatrix = function (matrix) {
  4586. var result = new Quaternion();
  4587. Quaternion.FromRotationMatrixToRef(matrix, result);
  4588. return result;
  4589. };
  4590. /**
  4591. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4592. */
  4593. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4594. var data = matrix.m;
  4595. var m11 = data[0], m12 = data[4], m13 = data[8];
  4596. var m21 = data[1], m22 = data[5], m23 = data[9];
  4597. var m31 = data[2], m32 = data[6], m33 = data[10];
  4598. var trace = m11 + m22 + m33;
  4599. var s;
  4600. if (trace > 0) {
  4601. s = 0.5 / Math.sqrt(trace + 1.0);
  4602. result.w = 0.25 / s;
  4603. result.x = (m32 - m23) * s;
  4604. result.y = (m13 - m31) * s;
  4605. result.z = (m21 - m12) * s;
  4606. }
  4607. else if (m11 > m22 && m11 > m33) {
  4608. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4609. result.w = (m32 - m23) / s;
  4610. result.x = 0.25 * s;
  4611. result.y = (m12 + m21) / s;
  4612. result.z = (m13 + m31) / s;
  4613. }
  4614. else if (m22 > m33) {
  4615. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4616. result.w = (m13 - m31) / s;
  4617. result.x = (m12 + m21) / s;
  4618. result.y = 0.25 * s;
  4619. result.z = (m23 + m32) / s;
  4620. }
  4621. else {
  4622. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4623. result.w = (m21 - m12) / s;
  4624. result.x = (m13 + m31) / s;
  4625. result.y = (m23 + m32) / s;
  4626. result.z = 0.25 * s;
  4627. }
  4628. };
  4629. /**
  4630. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4631. */
  4632. Quaternion.Zero = function () {
  4633. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4634. };
  4635. /**
  4636. * Returns a new Quaternion as the inverted current Quaternion.
  4637. */
  4638. Quaternion.Inverse = function (q) {
  4639. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4640. };
  4641. /**
  4642. * Returns the identity Quaternion.
  4643. */
  4644. Quaternion.Identity = function () {
  4645. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4646. };
  4647. Quaternion.IsIdentity = function (quaternion) {
  4648. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4649. };
  4650. /**
  4651. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4652. */
  4653. Quaternion.RotationAxis = function (axis, angle) {
  4654. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4655. };
  4656. /**
  4657. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4658. */
  4659. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4660. var sin = Math.sin(angle / 2);
  4661. axis.normalize();
  4662. result.w = Math.cos(angle / 2);
  4663. result.x = axis.x * sin;
  4664. result.y = axis.y * sin;
  4665. result.z = axis.z * sin;
  4666. return result;
  4667. };
  4668. /**
  4669. * Retuns a new Quaternion set from the starting index of the passed array.
  4670. */
  4671. Quaternion.FromArray = function (array, offset) {
  4672. if (!offset) {
  4673. offset = 0;
  4674. }
  4675. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4676. };
  4677. /**
  4678. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4679. */
  4680. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4681. var q = new Quaternion();
  4682. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4683. return q;
  4684. };
  4685. /**
  4686. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4687. */
  4688. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4689. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4690. var halfRoll = roll * 0.5;
  4691. var halfPitch = pitch * 0.5;
  4692. var halfYaw = yaw * 0.5;
  4693. var sinRoll = Math.sin(halfRoll);
  4694. var cosRoll = Math.cos(halfRoll);
  4695. var sinPitch = Math.sin(halfPitch);
  4696. var cosPitch = Math.cos(halfPitch);
  4697. var sinYaw = Math.sin(halfYaw);
  4698. var cosYaw = Math.cos(halfYaw);
  4699. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4700. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4701. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4702. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4703. };
  4704. /**
  4705. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4706. */
  4707. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4708. var result = new Quaternion();
  4709. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4710. return result;
  4711. };
  4712. /**
  4713. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4714. */
  4715. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4716. // Produces a quaternion from Euler angles in the z-x-z orientation
  4717. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4718. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4719. var halfBeta = beta * 0.5;
  4720. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4721. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4722. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4723. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4724. };
  4725. /**
  4726. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4727. * cf to Vector3.RotationFromAxis() documentation.
  4728. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4729. */
  4730. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4731. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4732. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4733. return quat;
  4734. };
  4735. /**
  4736. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4737. * cf to Vector3.RotationFromAxis() documentation.
  4738. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4739. */
  4740. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4741. var rotMat = MathTmp.Matrix[0];
  4742. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4743. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4744. };
  4745. Quaternion.Slerp = function (left, right, amount) {
  4746. var result = Quaternion.Identity();
  4747. Quaternion.SlerpToRef(left, right, amount, result);
  4748. return result;
  4749. };
  4750. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4751. var num2;
  4752. var num3;
  4753. var num = amount;
  4754. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4755. var flag = false;
  4756. if (num4 < 0) {
  4757. flag = true;
  4758. num4 = -num4;
  4759. }
  4760. if (num4 > 0.999999) {
  4761. num3 = 1 - num;
  4762. num2 = flag ? -num : num;
  4763. }
  4764. else {
  4765. var num5 = Math.acos(num4);
  4766. var num6 = (1.0 / Math.sin(num5));
  4767. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4768. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4769. }
  4770. result.x = (num3 * left.x) + (num2 * right.x);
  4771. result.y = (num3 * left.y) + (num2 * right.y);
  4772. result.z = (num3 * left.z) + (num2 * right.z);
  4773. result.w = (num3 * left.w) + (num2 * right.w);
  4774. };
  4775. /**
  4776. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4777. */
  4778. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4779. var squared = amount * amount;
  4780. var cubed = amount * squared;
  4781. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4782. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4783. var part3 = (cubed - (2.0 * squared)) + amount;
  4784. var part4 = cubed - squared;
  4785. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4786. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4787. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4788. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4789. return new Quaternion(x, y, z, w);
  4790. };
  4791. return Quaternion;
  4792. }());
  4793. BABYLON.Quaternion = Quaternion;
  4794. var Matrix = /** @class */ (function () {
  4795. function Matrix() {
  4796. this._isIdentity = false;
  4797. this._isIdentityDirty = true;
  4798. this.m = new Float32Array(16);
  4799. this._markAsUpdated();
  4800. }
  4801. Matrix.prototype._markAsUpdated = function () {
  4802. this.updateFlag = Matrix._updateFlagSeed++;
  4803. this._isIdentityDirty = true;
  4804. };
  4805. // Properties
  4806. /**
  4807. * Boolean : True is the matrix is the identity matrix
  4808. */
  4809. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4810. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4811. if (this._isIdentityDirty) {
  4812. this._isIdentityDirty = false;
  4813. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4814. this._isIdentity = false;
  4815. }
  4816. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4817. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4818. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4819. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4820. this._isIdentity = false;
  4821. }
  4822. else {
  4823. this._isIdentity = true;
  4824. }
  4825. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4826. this._isIdentity = false;
  4827. }
  4828. }
  4829. return this._isIdentity;
  4830. };
  4831. /**
  4832. * Returns the matrix determinant (float).
  4833. */
  4834. Matrix.prototype.determinant = function () {
  4835. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4836. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4837. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4838. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4839. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4840. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4841. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4842. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4843. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4844. };
  4845. // Methods
  4846. /**
  4847. * Returns the matrix underlying array.
  4848. */
  4849. Matrix.prototype.toArray = function () {
  4850. return this.m;
  4851. };
  4852. /**
  4853. * Returns the matrix underlying array.
  4854. */
  4855. Matrix.prototype.asArray = function () {
  4856. return this.toArray();
  4857. };
  4858. /**
  4859. * Inverts in place the Matrix.
  4860. * Returns the Matrix inverted.
  4861. */
  4862. Matrix.prototype.invert = function () {
  4863. this.invertToRef(this);
  4864. return this;
  4865. };
  4866. /**
  4867. * Sets all the matrix elements to zero.
  4868. * Returns the Matrix.
  4869. */
  4870. Matrix.prototype.reset = function () {
  4871. for (var index = 0; index < 16; index++) {
  4872. this.m[index] = 0.0;
  4873. }
  4874. this._markAsUpdated();
  4875. return this;
  4876. };
  4877. /**
  4878. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4879. */
  4880. Matrix.prototype.add = function (other) {
  4881. var result = new Matrix();
  4882. this.addToRef(other, result);
  4883. return result;
  4884. };
  4885. /**
  4886. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4887. * Returns the Matrix.
  4888. */
  4889. Matrix.prototype.addToRef = function (other, result) {
  4890. for (var index = 0; index < 16; index++) {
  4891. result.m[index] = this.m[index] + other.m[index];
  4892. }
  4893. result._markAsUpdated();
  4894. return this;
  4895. };
  4896. /**
  4897. * Adds in place the passed matrix to the current Matrix.
  4898. * Returns the updated Matrix.
  4899. */
  4900. Matrix.prototype.addToSelf = function (other) {
  4901. for (var index = 0; index < 16; index++) {
  4902. this.m[index] += other.m[index];
  4903. }
  4904. this._markAsUpdated();
  4905. return this;
  4906. };
  4907. /**
  4908. * Sets the passed matrix with the current inverted Matrix.
  4909. * Returns the unmodified current Matrix.
  4910. */
  4911. Matrix.prototype.invertToRef = function (other) {
  4912. var l1 = this.m[0];
  4913. var l2 = this.m[1];
  4914. var l3 = this.m[2];
  4915. var l4 = this.m[3];
  4916. var l5 = this.m[4];
  4917. var l6 = this.m[5];
  4918. var l7 = this.m[6];
  4919. var l8 = this.m[7];
  4920. var l9 = this.m[8];
  4921. var l10 = this.m[9];
  4922. var l11 = this.m[10];
  4923. var l12 = this.m[11];
  4924. var l13 = this.m[12];
  4925. var l14 = this.m[13];
  4926. var l15 = this.m[14];
  4927. var l16 = this.m[15];
  4928. var l17 = (l11 * l16) - (l12 * l15);
  4929. var l18 = (l10 * l16) - (l12 * l14);
  4930. var l19 = (l10 * l15) - (l11 * l14);
  4931. var l20 = (l9 * l16) - (l12 * l13);
  4932. var l21 = (l9 * l15) - (l11 * l13);
  4933. var l22 = (l9 * l14) - (l10 * l13);
  4934. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4935. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4936. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4937. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4938. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4939. var l28 = (l7 * l16) - (l8 * l15);
  4940. var l29 = (l6 * l16) - (l8 * l14);
  4941. var l30 = (l6 * l15) - (l7 * l14);
  4942. var l31 = (l5 * l16) - (l8 * l13);
  4943. var l32 = (l5 * l15) - (l7 * l13);
  4944. var l33 = (l5 * l14) - (l6 * l13);
  4945. var l34 = (l7 * l12) - (l8 * l11);
  4946. var l35 = (l6 * l12) - (l8 * l10);
  4947. var l36 = (l6 * l11) - (l7 * l10);
  4948. var l37 = (l5 * l12) - (l8 * l9);
  4949. var l38 = (l5 * l11) - (l7 * l9);
  4950. var l39 = (l5 * l10) - (l6 * l9);
  4951. other.m[0] = l23 * l27;
  4952. other.m[4] = l24 * l27;
  4953. other.m[8] = l25 * l27;
  4954. other.m[12] = l26 * l27;
  4955. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4956. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4957. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4958. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4959. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4960. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4961. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4962. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4963. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4964. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4965. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4966. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4967. other._markAsUpdated();
  4968. return this;
  4969. };
  4970. /**
  4971. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4972. * Returns the updated Matrix.
  4973. */
  4974. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4975. this.m[12] = x;
  4976. this.m[13] = y;
  4977. this.m[14] = z;
  4978. this._markAsUpdated();
  4979. return this;
  4980. };
  4981. /**
  4982. * Inserts the translation vector in the current Matrix.
  4983. * Returns the updated Matrix.
  4984. */
  4985. Matrix.prototype.setTranslation = function (vector3) {
  4986. this.m[12] = vector3.x;
  4987. this.m[13] = vector3.y;
  4988. this.m[14] = vector3.z;
  4989. this._markAsUpdated();
  4990. return this;
  4991. };
  4992. /**
  4993. * Returns a new Vector3 as the extracted translation from the Matrix.
  4994. */
  4995. Matrix.prototype.getTranslation = function () {
  4996. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4997. };
  4998. /**
  4999. * Fill a Vector3 with the extracted translation from the Matrix.
  5000. */
  5001. Matrix.prototype.getTranslationToRef = function (result) {
  5002. result.x = this.m[12];
  5003. result.y = this.m[13];
  5004. result.z = this.m[14];
  5005. return this;
  5006. };
  5007. /**
  5008. * Remove rotation and scaling part from the Matrix.
  5009. * Returns the updated Matrix.
  5010. */
  5011. Matrix.prototype.removeRotationAndScaling = function () {
  5012. this.setRowFromFloats(0, 1, 0, 0, 0);
  5013. this.setRowFromFloats(1, 0, 1, 0, 0);
  5014. this.setRowFromFloats(2, 0, 0, 1, 0);
  5015. return this;
  5016. };
  5017. /**
  5018. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  5019. */
  5020. Matrix.prototype.multiply = function (other) {
  5021. var result = new Matrix();
  5022. this.multiplyToRef(other, result);
  5023. return result;
  5024. };
  5025. /**
  5026. * Updates the current Matrix from the passed one values.
  5027. * Returns the updated Matrix.
  5028. */
  5029. Matrix.prototype.copyFrom = function (other) {
  5030. for (var index = 0; index < 16; index++) {
  5031. this.m[index] = other.m[index];
  5032. }
  5033. this._markAsUpdated();
  5034. return this;
  5035. };
  5036. /**
  5037. * Populates the passed array from the starting index with the Matrix values.
  5038. * Returns the Matrix.
  5039. */
  5040. Matrix.prototype.copyToArray = function (array, offset) {
  5041. if (offset === void 0) { offset = 0; }
  5042. for (var index = 0; index < 16; index++) {
  5043. array[offset + index] = this.m[index];
  5044. }
  5045. return this;
  5046. };
  5047. /**
  5048. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  5049. */
  5050. Matrix.prototype.multiplyToRef = function (other, result) {
  5051. this.multiplyToArray(other, result.m, 0);
  5052. result._markAsUpdated();
  5053. return this;
  5054. };
  5055. /**
  5056. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  5057. */
  5058. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5059. var tm0 = this.m[0];
  5060. var tm1 = this.m[1];
  5061. var tm2 = this.m[2];
  5062. var tm3 = this.m[3];
  5063. var tm4 = this.m[4];
  5064. var tm5 = this.m[5];
  5065. var tm6 = this.m[6];
  5066. var tm7 = this.m[7];
  5067. var tm8 = this.m[8];
  5068. var tm9 = this.m[9];
  5069. var tm10 = this.m[10];
  5070. var tm11 = this.m[11];
  5071. var tm12 = this.m[12];
  5072. var tm13 = this.m[13];
  5073. var tm14 = this.m[14];
  5074. var tm15 = this.m[15];
  5075. var om0 = other.m[0];
  5076. var om1 = other.m[1];
  5077. var om2 = other.m[2];
  5078. var om3 = other.m[3];
  5079. var om4 = other.m[4];
  5080. var om5 = other.m[5];
  5081. var om6 = other.m[6];
  5082. var om7 = other.m[7];
  5083. var om8 = other.m[8];
  5084. var om9 = other.m[9];
  5085. var om10 = other.m[10];
  5086. var om11 = other.m[11];
  5087. var om12 = other.m[12];
  5088. var om13 = other.m[13];
  5089. var om14 = other.m[14];
  5090. var om15 = other.m[15];
  5091. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5092. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5093. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5094. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5095. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5096. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5097. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5098. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5099. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5100. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5101. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5102. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5103. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5104. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5105. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5106. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5107. return this;
  5108. };
  5109. /**
  5110. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5111. */
  5112. Matrix.prototype.equals = function (value) {
  5113. return value &&
  5114. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5115. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5116. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5117. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5118. };
  5119. /**
  5120. * Returns a new Matrix from the current Matrix.
  5121. */
  5122. Matrix.prototype.clone = function () {
  5123. 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]);
  5124. };
  5125. /**
  5126. * Returns the string "Matrix"
  5127. */
  5128. Matrix.prototype.getClassName = function () {
  5129. return "Matrix";
  5130. };
  5131. /**
  5132. * Returns the Matrix hash code.
  5133. */
  5134. Matrix.prototype.getHashCode = function () {
  5135. var hash = this.m[0] || 0;
  5136. for (var i = 1; i < 16; i++) {
  5137. hash = (hash * 397) ^ (this.m[i] || 0);
  5138. }
  5139. return hash;
  5140. };
  5141. /**
  5142. * Decomposes the current Matrix into :
  5143. * - a scale vector3 passed as a reference to update,
  5144. * - a rotation quaternion passed as a reference to update,
  5145. * - a translation vector3 passed as a reference to update.
  5146. * Returns the true if operation was successful.
  5147. */
  5148. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5149. translation.x = this.m[12];
  5150. translation.y = this.m[13];
  5151. translation.z = this.m[14];
  5152. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5153. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5154. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5155. if (this.determinant() <= 0) {
  5156. scale.y *= -1;
  5157. }
  5158. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5159. rotation.x = 0;
  5160. rotation.y = 0;
  5161. rotation.z = 0;
  5162. rotation.w = 1;
  5163. return false;
  5164. }
  5165. 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]);
  5166. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5167. return true;
  5168. };
  5169. /**
  5170. * Returns the index-th row of the current matrix as a new Vector4.
  5171. */
  5172. Matrix.prototype.getRow = function (index) {
  5173. if (index < 0 || index > 3) {
  5174. return null;
  5175. }
  5176. var i = index * 4;
  5177. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5178. };
  5179. /**
  5180. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5181. * Returns the updated Matrix.
  5182. */
  5183. Matrix.prototype.setRow = function (index, row) {
  5184. if (index < 0 || index > 3) {
  5185. return this;
  5186. }
  5187. var i = index * 4;
  5188. this.m[i + 0] = row.x;
  5189. this.m[i + 1] = row.y;
  5190. this.m[i + 2] = row.z;
  5191. this.m[i + 3] = row.w;
  5192. this._markAsUpdated();
  5193. return this;
  5194. };
  5195. /**
  5196. * Compute the transpose of the matrix.
  5197. * Returns a new Matrix.
  5198. */
  5199. Matrix.prototype.transpose = function () {
  5200. return Matrix.Transpose(this);
  5201. };
  5202. /**
  5203. * Compute the transpose of the matrix.
  5204. * Returns the current matrix.
  5205. */
  5206. Matrix.prototype.transposeToRef = function (result) {
  5207. Matrix.TransposeToRef(this, result);
  5208. return this;
  5209. };
  5210. /**
  5211. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5212. * Returns the updated Matrix.
  5213. */
  5214. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5215. if (index < 0 || index > 3) {
  5216. return this;
  5217. }
  5218. var i = index * 4;
  5219. this.m[i + 0] = x;
  5220. this.m[i + 1] = y;
  5221. this.m[i + 2] = z;
  5222. this.m[i + 3] = w;
  5223. this._markAsUpdated();
  5224. return this;
  5225. };
  5226. /**
  5227. * Compute a new Matrix set with the current Matrix values multiplied by scale (float)
  5228. * @param scale defines the scale factor
  5229. * @returns a new Matrix
  5230. */
  5231. Matrix.prototype.scale = function (scale) {
  5232. var result = new Matrix();
  5233. this.scaleToRef(scale, result);
  5234. return result;
  5235. };
  5236. /**
  5237. * Scale the current Matrix values by a factor to a given result Matrix
  5238. * @param scale defines the scale factor
  5239. * @param result defines the Matrix to store the result
  5240. * @returns the current Matrix
  5241. */
  5242. Matrix.prototype.scaleToRef = function (scale, result) {
  5243. for (var index = 0; index < 16; index++) {
  5244. result.m[index] = this.m[index] * scale;
  5245. }
  5246. result._markAsUpdated();
  5247. return this;
  5248. };
  5249. /**
  5250. * Scale the current Matrix values by a factor and add the result to a given Matrix
  5251. * @param scale defines the scale factor
  5252. * @param result defines the Matrix to store the result
  5253. * @returns the current Matrix
  5254. */
  5255. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5256. for (var index = 0; index < 16; index++) {
  5257. result.m[index] += this.m[index] * scale;
  5258. }
  5259. result._markAsUpdated();
  5260. return this;
  5261. };
  5262. /**
  5263. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5264. * @param ref matrix to store the result
  5265. */
  5266. Matrix.prototype.toNormalMatrix = function (ref) {
  5267. this.invertToRef(ref);
  5268. ref.transpose();
  5269. var m = ref.m;
  5270. 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);
  5271. };
  5272. /**
  5273. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5274. */
  5275. Matrix.prototype.getRotationMatrix = function () {
  5276. var result = Matrix.Identity();
  5277. this.getRotationMatrixToRef(result);
  5278. return result;
  5279. };
  5280. /**
  5281. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5282. * Returns the current Matrix.
  5283. */
  5284. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5285. var m = this.m;
  5286. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5287. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5288. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5289. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5290. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5291. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5292. 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);
  5293. return this;
  5294. };
  5295. // Statics
  5296. /**
  5297. * Returns a new Matrix set from the starting index of the passed array.
  5298. */
  5299. Matrix.FromArray = function (array, offset) {
  5300. var result = new Matrix();
  5301. if (!offset) {
  5302. offset = 0;
  5303. }
  5304. Matrix.FromArrayToRef(array, offset, result);
  5305. return result;
  5306. };
  5307. /**
  5308. * Sets the passed "result" matrix from the starting index of the passed array.
  5309. */
  5310. Matrix.FromArrayToRef = function (array, offset, result) {
  5311. for (var index = 0; index < 16; index++) {
  5312. result.m[index] = array[index + offset];
  5313. }
  5314. result._markAsUpdated();
  5315. };
  5316. /**
  5317. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5318. */
  5319. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5320. for (var index = 0; index < 16; index++) {
  5321. result.m[index] = array[index + offset] * scale;
  5322. }
  5323. result._markAsUpdated();
  5324. };
  5325. /**
  5326. * Sets the passed matrix "result" with the 16 passed floats.
  5327. */
  5328. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5329. result.m[0] = initialM11;
  5330. result.m[1] = initialM12;
  5331. result.m[2] = initialM13;
  5332. result.m[3] = initialM14;
  5333. result.m[4] = initialM21;
  5334. result.m[5] = initialM22;
  5335. result.m[6] = initialM23;
  5336. result.m[7] = initialM24;
  5337. result.m[8] = initialM31;
  5338. result.m[9] = initialM32;
  5339. result.m[10] = initialM33;
  5340. result.m[11] = initialM34;
  5341. result.m[12] = initialM41;
  5342. result.m[13] = initialM42;
  5343. result.m[14] = initialM43;
  5344. result.m[15] = initialM44;
  5345. result._markAsUpdated();
  5346. };
  5347. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5348. /**
  5349. * Static identity matrix to be used as readonly matrix
  5350. * Must not be updated.
  5351. */
  5352. get: function () {
  5353. return Matrix._identityReadOnly;
  5354. },
  5355. enumerable: true,
  5356. configurable: true
  5357. });
  5358. /**
  5359. * Returns a new Matrix set from the 16 passed floats.
  5360. */
  5361. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5362. var result = new Matrix();
  5363. result.m[0] = initialM11;
  5364. result.m[1] = initialM12;
  5365. result.m[2] = initialM13;
  5366. result.m[3] = initialM14;
  5367. result.m[4] = initialM21;
  5368. result.m[5] = initialM22;
  5369. result.m[6] = initialM23;
  5370. result.m[7] = initialM24;
  5371. result.m[8] = initialM31;
  5372. result.m[9] = initialM32;
  5373. result.m[10] = initialM33;
  5374. result.m[11] = initialM34;
  5375. result.m[12] = initialM41;
  5376. result.m[13] = initialM42;
  5377. result.m[14] = initialM43;
  5378. result.m[15] = initialM44;
  5379. return result;
  5380. };
  5381. /**
  5382. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5383. */
  5384. Matrix.Compose = function (scale, rotation, translation) {
  5385. var result = Matrix.Identity();
  5386. Matrix.ComposeToRef(scale, rotation, translation, result);
  5387. return result;
  5388. };
  5389. /**
  5390. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5391. */
  5392. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5393. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5394. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5395. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5396. result.setTranslation(translation);
  5397. };
  5398. /**
  5399. * Returns a new indentity Matrix.
  5400. */
  5401. Matrix.Identity = function () {
  5402. 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);
  5403. };
  5404. /**
  5405. * Sets the passed "result" as an identity matrix.
  5406. */
  5407. Matrix.IdentityToRef = function (result) {
  5408. 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);
  5409. };
  5410. /**
  5411. * Returns a new zero Matrix.
  5412. */
  5413. Matrix.Zero = function () {
  5414. 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);
  5415. };
  5416. /**
  5417. * Returns a new rotation matrix for "angle" radians around the X axis.
  5418. */
  5419. Matrix.RotationX = function (angle) {
  5420. var result = new Matrix();
  5421. Matrix.RotationXToRef(angle, result);
  5422. return result;
  5423. };
  5424. /**
  5425. * Returns a new Matrix as the passed inverted one.
  5426. */
  5427. Matrix.Invert = function (source) {
  5428. var result = new Matrix();
  5429. source.invertToRef(result);
  5430. return result;
  5431. };
  5432. /**
  5433. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5434. */
  5435. Matrix.RotationXToRef = function (angle, result) {
  5436. var s = Math.sin(angle);
  5437. var c = Math.cos(angle);
  5438. result.m[0] = 1.0;
  5439. result.m[15] = 1.0;
  5440. result.m[5] = c;
  5441. result.m[10] = c;
  5442. result.m[9] = -s;
  5443. result.m[6] = s;
  5444. result.m[1] = 0.0;
  5445. result.m[2] = 0.0;
  5446. result.m[3] = 0.0;
  5447. result.m[4] = 0.0;
  5448. result.m[7] = 0.0;
  5449. result.m[8] = 0.0;
  5450. result.m[11] = 0.0;
  5451. result.m[12] = 0.0;
  5452. result.m[13] = 0.0;
  5453. result.m[14] = 0.0;
  5454. result._markAsUpdated();
  5455. };
  5456. /**
  5457. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5458. */
  5459. Matrix.RotationY = function (angle) {
  5460. var result = new Matrix();
  5461. Matrix.RotationYToRef(angle, result);
  5462. return result;
  5463. };
  5464. /**
  5465. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5466. */
  5467. Matrix.RotationYToRef = function (angle, result) {
  5468. var s = Math.sin(angle);
  5469. var c = Math.cos(angle);
  5470. result.m[5] = 1.0;
  5471. result.m[15] = 1.0;
  5472. result.m[0] = c;
  5473. result.m[2] = -s;
  5474. result.m[8] = s;
  5475. result.m[10] = c;
  5476. result.m[1] = 0.0;
  5477. result.m[3] = 0.0;
  5478. result.m[4] = 0.0;
  5479. result.m[6] = 0.0;
  5480. result.m[7] = 0.0;
  5481. result.m[9] = 0.0;
  5482. result.m[11] = 0.0;
  5483. result.m[12] = 0.0;
  5484. result.m[13] = 0.0;
  5485. result.m[14] = 0.0;
  5486. result._markAsUpdated();
  5487. };
  5488. /**
  5489. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5490. */
  5491. Matrix.RotationZ = function (angle) {
  5492. var result = new Matrix();
  5493. Matrix.RotationZToRef(angle, result);
  5494. return result;
  5495. };
  5496. /**
  5497. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5498. */
  5499. Matrix.RotationZToRef = function (angle, result) {
  5500. var s = Math.sin(angle);
  5501. var c = Math.cos(angle);
  5502. result.m[10] = 1.0;
  5503. result.m[15] = 1.0;
  5504. result.m[0] = c;
  5505. result.m[1] = s;
  5506. result.m[4] = -s;
  5507. result.m[5] = c;
  5508. result.m[2] = 0.0;
  5509. result.m[3] = 0.0;
  5510. result.m[6] = 0.0;
  5511. result.m[7] = 0.0;
  5512. result.m[8] = 0.0;
  5513. result.m[9] = 0.0;
  5514. result.m[11] = 0.0;
  5515. result.m[12] = 0.0;
  5516. result.m[13] = 0.0;
  5517. result.m[14] = 0.0;
  5518. result._markAsUpdated();
  5519. };
  5520. /**
  5521. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5522. */
  5523. Matrix.RotationAxis = function (axis, angle) {
  5524. var result = Matrix.Zero();
  5525. Matrix.RotationAxisToRef(axis, angle, result);
  5526. return result;
  5527. };
  5528. /**
  5529. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5530. */
  5531. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5532. var s = Math.sin(-angle);
  5533. var c = Math.cos(-angle);
  5534. var c1 = 1 - c;
  5535. axis.normalize();
  5536. result.m[0] = (axis.x * axis.x) * c1 + c;
  5537. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5538. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5539. result.m[3] = 0.0;
  5540. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5541. result.m[5] = (axis.y * axis.y) * c1 + c;
  5542. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5543. result.m[7] = 0.0;
  5544. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5545. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5546. result.m[10] = (axis.z * axis.z) * c1 + c;
  5547. result.m[11] = 0.0;
  5548. result.m[15] = 1.0;
  5549. result._markAsUpdated();
  5550. };
  5551. /**
  5552. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5553. */
  5554. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5555. var result = new Matrix();
  5556. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5557. return result;
  5558. };
  5559. /**
  5560. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5561. */
  5562. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5563. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5564. this._tempQuaternion.toRotationMatrix(result);
  5565. };
  5566. /**
  5567. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5568. */
  5569. Matrix.Scaling = function (x, y, z) {
  5570. var result = Matrix.Zero();
  5571. Matrix.ScalingToRef(x, y, z, result);
  5572. return result;
  5573. };
  5574. /**
  5575. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5576. */
  5577. Matrix.ScalingToRef = function (x, y, z, result) {
  5578. result.m[0] = x;
  5579. result.m[1] = 0.0;
  5580. result.m[2] = 0.0;
  5581. result.m[3] = 0.0;
  5582. result.m[4] = 0.0;
  5583. result.m[5] = y;
  5584. result.m[6] = 0.0;
  5585. result.m[7] = 0.0;
  5586. result.m[8] = 0.0;
  5587. result.m[9] = 0.0;
  5588. result.m[10] = z;
  5589. result.m[11] = 0.0;
  5590. result.m[12] = 0.0;
  5591. result.m[13] = 0.0;
  5592. result.m[14] = 0.0;
  5593. result.m[15] = 1.0;
  5594. result._markAsUpdated();
  5595. };
  5596. /**
  5597. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5598. */
  5599. Matrix.Translation = function (x, y, z) {
  5600. var result = Matrix.Identity();
  5601. Matrix.TranslationToRef(x, y, z, result);
  5602. return result;
  5603. };
  5604. /**
  5605. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5606. */
  5607. Matrix.TranslationToRef = function (x, y, z, result) {
  5608. 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);
  5609. };
  5610. /**
  5611. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5612. * @param startValue defines the start value
  5613. * @param endValue defines the end value
  5614. * @param gradient defines the gradient factor
  5615. * @returns the new matrix
  5616. */
  5617. Matrix.Lerp = function (startValue, endValue, gradient) {
  5618. var result = Matrix.Zero();
  5619. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5620. return result;
  5621. };
  5622. /**
  5623. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5624. * @param startValue defines the start value
  5625. * @param endValue defines the end value
  5626. * @param gradient defines the gradient factor
  5627. * @param result defines the Matrix object where to store data
  5628. */
  5629. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5630. for (var index = 0; index < 16; index++) {
  5631. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5632. }
  5633. result._markAsUpdated();
  5634. };
  5635. /**
  5636. * Returns a new Matrix whose values are computed by :
  5637. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5638. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5639. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5640. */
  5641. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5642. var startScale = new Vector3(0, 0, 0);
  5643. var startRotation = new Quaternion();
  5644. var startTranslation = new Vector3(0, 0, 0);
  5645. startValue.decompose(startScale, startRotation, startTranslation);
  5646. var endScale = new Vector3(0, 0, 0);
  5647. var endRotation = new Quaternion();
  5648. var endTranslation = new Vector3(0, 0, 0);
  5649. endValue.decompose(endScale, endRotation, endTranslation);
  5650. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5651. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5652. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5653. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5654. };
  5655. /**
  5656. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5657. * This methods works for a Left-Handed system.
  5658. */
  5659. Matrix.LookAtLH = function (eye, target, up) {
  5660. var result = Matrix.Zero();
  5661. Matrix.LookAtLHToRef(eye, target, up, result);
  5662. return result;
  5663. };
  5664. /**
  5665. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5666. * This methods works for a Left-Handed system.
  5667. */
  5668. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5669. // Z axis
  5670. target.subtractToRef(eye, this._zAxis);
  5671. this._zAxis.normalize();
  5672. // X axis
  5673. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5674. if (this._xAxis.lengthSquared() === 0) {
  5675. this._xAxis.x = 1.0;
  5676. }
  5677. else {
  5678. this._xAxis.normalize();
  5679. }
  5680. // Y axis
  5681. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5682. this._yAxis.normalize();
  5683. // Eye angles
  5684. var ex = -Vector3.Dot(this._xAxis, eye);
  5685. var ey = -Vector3.Dot(this._yAxis, eye);
  5686. var ez = -Vector3.Dot(this._zAxis, eye);
  5687. 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);
  5688. };
  5689. /**
  5690. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5691. * This methods works for a Right-Handed system.
  5692. */
  5693. Matrix.LookAtRH = function (eye, target, up) {
  5694. var result = Matrix.Zero();
  5695. Matrix.LookAtRHToRef(eye, target, up, result);
  5696. return result;
  5697. };
  5698. /**
  5699. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5700. * This methods works for a Left-Handed system.
  5701. */
  5702. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5703. // Z axis
  5704. eye.subtractToRef(target, this._zAxis);
  5705. this._zAxis.normalize();
  5706. // X axis
  5707. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5708. if (this._xAxis.lengthSquared() === 0) {
  5709. this._xAxis.x = 1.0;
  5710. }
  5711. else {
  5712. this._xAxis.normalize();
  5713. }
  5714. // Y axis
  5715. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5716. this._yAxis.normalize();
  5717. // Eye angles
  5718. var ex = -Vector3.Dot(this._xAxis, eye);
  5719. var ey = -Vector3.Dot(this._yAxis, eye);
  5720. var ez = -Vector3.Dot(this._zAxis, eye);
  5721. 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);
  5722. };
  5723. /**
  5724. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5725. */
  5726. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5727. var matrix = Matrix.Zero();
  5728. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5729. return matrix;
  5730. };
  5731. /**
  5732. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5733. */
  5734. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5735. var n = znear;
  5736. var f = zfar;
  5737. var a = 2.0 / width;
  5738. var b = 2.0 / height;
  5739. var c = 2.0 / (f - n);
  5740. var d = -(f + n) / (f - n);
  5741. 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);
  5742. };
  5743. /**
  5744. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5745. */
  5746. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5747. var matrix = Matrix.Zero();
  5748. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5749. return matrix;
  5750. };
  5751. /**
  5752. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5753. */
  5754. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5755. var n = znear;
  5756. var f = zfar;
  5757. var a = 2.0 / (right - left);
  5758. var b = 2.0 / (top - bottom);
  5759. var c = 2.0 / (f - n);
  5760. var d = -(f + n) / (f - n);
  5761. var i0 = (left + right) / (left - right);
  5762. var i1 = (top + bottom) / (bottom - top);
  5763. 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);
  5764. };
  5765. /**
  5766. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5767. */
  5768. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5769. var matrix = Matrix.Zero();
  5770. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5771. return matrix;
  5772. };
  5773. /**
  5774. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5775. */
  5776. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5777. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5778. result.m[10] *= -1.0;
  5779. };
  5780. /**
  5781. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5782. */
  5783. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5784. var matrix = Matrix.Zero();
  5785. var n = znear;
  5786. var f = zfar;
  5787. var a = 2.0 * n / width;
  5788. var b = 2.0 * n / height;
  5789. var c = (f + n) / (f - n);
  5790. var d = -2.0 * f * n / (f - n);
  5791. 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);
  5792. return matrix;
  5793. };
  5794. /**
  5795. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5796. */
  5797. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5798. var matrix = Matrix.Zero();
  5799. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5800. return matrix;
  5801. };
  5802. /**
  5803. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5804. */
  5805. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5806. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5807. var n = znear;
  5808. var f = zfar;
  5809. var t = 1.0 / (Math.tan(fov * 0.5));
  5810. var a = isVerticalFovFixed ? (t / aspect) : t;
  5811. var b = isVerticalFovFixed ? t : (t * aspect);
  5812. var c = (f + n) / (f - n);
  5813. var d = -2.0 * f * n / (f - n);
  5814. 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);
  5815. };
  5816. /**
  5817. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5818. */
  5819. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5820. var matrix = Matrix.Zero();
  5821. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5822. return matrix;
  5823. };
  5824. /**
  5825. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5826. */
  5827. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5828. //alternatively this could be expressed as:
  5829. // m = PerspectiveFovLHToRef
  5830. // m[10] *= -1.0;
  5831. // m[11] *= -1.0;
  5832. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5833. var n = znear;
  5834. var f = zfar;
  5835. var t = 1.0 / (Math.tan(fov * 0.5));
  5836. var a = isVerticalFovFixed ? (t / aspect) : t;
  5837. var b = isVerticalFovFixed ? t : (t * aspect);
  5838. var c = -(f + n) / (f - n);
  5839. var d = -2 * f * n / (f - n);
  5840. 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);
  5841. };
  5842. /**
  5843. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5844. */
  5845. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5846. if (rightHanded === void 0) { rightHanded = false; }
  5847. var rightHandedFactor = rightHanded ? -1 : 1;
  5848. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5849. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5850. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5851. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5852. var xScale = 2.0 / (leftTan + rightTan);
  5853. var yScale = 2.0 / (upTan + downTan);
  5854. result.m[0] = xScale;
  5855. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5856. result.m[5] = yScale;
  5857. result.m[6] = result.m[7] = 0.0;
  5858. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5859. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5860. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5861. result.m[10] = -zfar / (znear - zfar);
  5862. result.m[11] = 1.0 * rightHandedFactor;
  5863. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5864. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5865. // result.m[14] = (znear * zfar) / (znear - zfar);
  5866. result._markAsUpdated();
  5867. };
  5868. /**
  5869. * Returns the final transformation matrix : world * view * projection * viewport
  5870. */
  5871. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5872. var cw = viewport.width;
  5873. var ch = viewport.height;
  5874. var cx = viewport.x;
  5875. var cy = viewport.y;
  5876. 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);
  5877. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5878. };
  5879. /**
  5880. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5881. */
  5882. Matrix.GetAsMatrix2x2 = function (matrix) {
  5883. return new Float32Array([
  5884. matrix.m[0], matrix.m[1],
  5885. matrix.m[4], matrix.m[5]
  5886. ]);
  5887. };
  5888. /**
  5889. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5890. */
  5891. Matrix.GetAsMatrix3x3 = function (matrix) {
  5892. return new Float32Array([
  5893. matrix.m[0], matrix.m[1], matrix.m[2],
  5894. matrix.m[4], matrix.m[5], matrix.m[6],
  5895. matrix.m[8], matrix.m[9], matrix.m[10]
  5896. ]);
  5897. };
  5898. /**
  5899. * Compute the transpose of the passed Matrix.
  5900. * Returns a new Matrix.
  5901. */
  5902. Matrix.Transpose = function (matrix) {
  5903. var result = new Matrix();
  5904. Matrix.TransposeToRef(matrix, result);
  5905. return result;
  5906. };
  5907. /**
  5908. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5909. */
  5910. Matrix.TransposeToRef = function (matrix, result) {
  5911. result.m[0] = matrix.m[0];
  5912. result.m[1] = matrix.m[4];
  5913. result.m[2] = matrix.m[8];
  5914. result.m[3] = matrix.m[12];
  5915. result.m[4] = matrix.m[1];
  5916. result.m[5] = matrix.m[5];
  5917. result.m[6] = matrix.m[9];
  5918. result.m[7] = matrix.m[13];
  5919. result.m[8] = matrix.m[2];
  5920. result.m[9] = matrix.m[6];
  5921. result.m[10] = matrix.m[10];
  5922. result.m[11] = matrix.m[14];
  5923. result.m[12] = matrix.m[3];
  5924. result.m[13] = matrix.m[7];
  5925. result.m[14] = matrix.m[11];
  5926. result.m[15] = matrix.m[15];
  5927. };
  5928. /**
  5929. * Returns a new Matrix as the reflection matrix across the passed plane.
  5930. */
  5931. Matrix.Reflection = function (plane) {
  5932. var matrix = new Matrix();
  5933. Matrix.ReflectionToRef(plane, matrix);
  5934. return matrix;
  5935. };
  5936. /**
  5937. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5938. */
  5939. Matrix.ReflectionToRef = function (plane, result) {
  5940. plane.normalize();
  5941. var x = plane.normal.x;
  5942. var y = plane.normal.y;
  5943. var z = plane.normal.z;
  5944. var temp = -2 * x;
  5945. var temp2 = -2 * y;
  5946. var temp3 = -2 * z;
  5947. result.m[0] = (temp * x) + 1;
  5948. result.m[1] = temp2 * x;
  5949. result.m[2] = temp3 * x;
  5950. result.m[3] = 0.0;
  5951. result.m[4] = temp * y;
  5952. result.m[5] = (temp2 * y) + 1;
  5953. result.m[6] = temp3 * y;
  5954. result.m[7] = 0.0;
  5955. result.m[8] = temp * z;
  5956. result.m[9] = temp2 * z;
  5957. result.m[10] = (temp3 * z) + 1;
  5958. result.m[11] = 0.0;
  5959. result.m[12] = temp * plane.d;
  5960. result.m[13] = temp2 * plane.d;
  5961. result.m[14] = temp3 * plane.d;
  5962. result.m[15] = 1.0;
  5963. result._markAsUpdated();
  5964. };
  5965. /**
  5966. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5967. */
  5968. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5969. result.m[0] = xaxis.x;
  5970. result.m[1] = xaxis.y;
  5971. result.m[2] = xaxis.z;
  5972. result.m[3] = 0.0;
  5973. result.m[4] = yaxis.x;
  5974. result.m[5] = yaxis.y;
  5975. result.m[6] = yaxis.z;
  5976. result.m[7] = 0.0;
  5977. result.m[8] = zaxis.x;
  5978. result.m[9] = zaxis.y;
  5979. result.m[10] = zaxis.z;
  5980. result.m[11] = 0.0;
  5981. result.m[12] = 0.0;
  5982. result.m[13] = 0.0;
  5983. result.m[14] = 0.0;
  5984. result.m[15] = 1.0;
  5985. result._markAsUpdated();
  5986. };
  5987. /**
  5988. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5989. */
  5990. Matrix.FromQuaternionToRef = function (quat, result) {
  5991. var xx = quat.x * quat.x;
  5992. var yy = quat.y * quat.y;
  5993. var zz = quat.z * quat.z;
  5994. var xy = quat.x * quat.y;
  5995. var zw = quat.z * quat.w;
  5996. var zx = quat.z * quat.x;
  5997. var yw = quat.y * quat.w;
  5998. var yz = quat.y * quat.z;
  5999. var xw = quat.x * quat.w;
  6000. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6001. result.m[1] = 2.0 * (xy + zw);
  6002. result.m[2] = 2.0 * (zx - yw);
  6003. result.m[3] = 0.0;
  6004. result.m[4] = 2.0 * (xy - zw);
  6005. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6006. result.m[6] = 2.0 * (yz + xw);
  6007. result.m[7] = 0.0;
  6008. result.m[8] = 2.0 * (zx + yw);
  6009. result.m[9] = 2.0 * (yz - xw);
  6010. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6011. result.m[11] = 0.0;
  6012. result.m[12] = 0.0;
  6013. result.m[13] = 0.0;
  6014. result.m[14] = 0.0;
  6015. result.m[15] = 1.0;
  6016. result._markAsUpdated();
  6017. };
  6018. Matrix._tempQuaternion = new Quaternion();
  6019. Matrix._xAxis = Vector3.Zero();
  6020. Matrix._yAxis = Vector3.Zero();
  6021. Matrix._zAxis = Vector3.Zero();
  6022. Matrix._updateFlagSeed = 0;
  6023. Matrix._identityReadOnly = Matrix.Identity();
  6024. return Matrix;
  6025. }());
  6026. BABYLON.Matrix = Matrix;
  6027. var Plane = /** @class */ (function () {
  6028. /**
  6029. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6030. */
  6031. function Plane(a, b, c, d) {
  6032. this.normal = new Vector3(a, b, c);
  6033. this.d = d;
  6034. }
  6035. /**
  6036. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6037. */
  6038. Plane.prototype.asArray = function () {
  6039. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6040. };
  6041. // Methods
  6042. /**
  6043. * Returns a new plane copied from the current Plane.
  6044. */
  6045. Plane.prototype.clone = function () {
  6046. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6047. };
  6048. /**
  6049. * Returns the string "Plane".
  6050. */
  6051. Plane.prototype.getClassName = function () {
  6052. return "Plane";
  6053. };
  6054. /**
  6055. * Returns the Plane hash code.
  6056. */
  6057. Plane.prototype.getHashCode = function () {
  6058. var hash = this.normal.getHashCode();
  6059. hash = (hash * 397) ^ (this.d || 0);
  6060. return hash;
  6061. };
  6062. /**
  6063. * Normalize the current Plane in place.
  6064. * Returns the updated Plane.
  6065. */
  6066. Plane.prototype.normalize = function () {
  6067. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6068. var magnitude = 0.0;
  6069. if (norm !== 0) {
  6070. magnitude = 1.0 / norm;
  6071. }
  6072. this.normal.x *= magnitude;
  6073. this.normal.y *= magnitude;
  6074. this.normal.z *= magnitude;
  6075. this.d *= magnitude;
  6076. return this;
  6077. };
  6078. /**
  6079. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6080. */
  6081. Plane.prototype.transform = function (transformation) {
  6082. var transposedMatrix = Matrix.Transpose(transformation);
  6083. var x = this.normal.x;
  6084. var y = this.normal.y;
  6085. var z = this.normal.z;
  6086. var d = this.d;
  6087. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6088. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6089. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6090. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6091. return new Plane(normalX, normalY, normalZ, finalD);
  6092. };
  6093. /**
  6094. * Returns the dot product (float) of the point coordinates and the plane normal.
  6095. */
  6096. Plane.prototype.dotCoordinate = function (point) {
  6097. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6098. };
  6099. /**
  6100. * Updates the current Plane from the plane defined by the three passed points.
  6101. * Returns the updated Plane.
  6102. */
  6103. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6104. var x1 = point2.x - point1.x;
  6105. var y1 = point2.y - point1.y;
  6106. var z1 = point2.z - point1.z;
  6107. var x2 = point3.x - point1.x;
  6108. var y2 = point3.y - point1.y;
  6109. var z2 = point3.z - point1.z;
  6110. var yz = (y1 * z2) - (z1 * y2);
  6111. var xz = (z1 * x2) - (x1 * z2);
  6112. var xy = (x1 * y2) - (y1 * x2);
  6113. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6114. var invPyth;
  6115. if (pyth !== 0) {
  6116. invPyth = 1.0 / pyth;
  6117. }
  6118. else {
  6119. invPyth = 0.0;
  6120. }
  6121. this.normal.x = yz * invPyth;
  6122. this.normal.y = xz * invPyth;
  6123. this.normal.z = xy * invPyth;
  6124. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6125. return this;
  6126. };
  6127. /**
  6128. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6129. */
  6130. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6131. var dot = Vector3.Dot(this.normal, direction);
  6132. return (dot <= epsilon);
  6133. };
  6134. /**
  6135. * Returns the signed distance (float) from the passed point to the Plane.
  6136. */
  6137. Plane.prototype.signedDistanceTo = function (point) {
  6138. return Vector3.Dot(point, this.normal) + this.d;
  6139. };
  6140. // Statics
  6141. /**
  6142. * Returns a new Plane from the passed array.
  6143. */
  6144. Plane.FromArray = function (array) {
  6145. return new Plane(array[0], array[1], array[2], array[3]);
  6146. };
  6147. /**
  6148. * Returns a new Plane defined by the three passed points.
  6149. */
  6150. Plane.FromPoints = function (point1, point2, point3) {
  6151. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6152. result.copyFromPoints(point1, point2, point3);
  6153. return result;
  6154. };
  6155. /**
  6156. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6157. * Note : the vector "normal" is updated because normalized.
  6158. */
  6159. Plane.FromPositionAndNormal = function (origin, normal) {
  6160. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6161. normal.normalize();
  6162. result.normal = normal;
  6163. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6164. return result;
  6165. };
  6166. /**
  6167. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6168. */
  6169. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6170. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6171. return Vector3.Dot(point, normal) + d;
  6172. };
  6173. return Plane;
  6174. }());
  6175. BABYLON.Plane = Plane;
  6176. var Viewport = /** @class */ (function () {
  6177. /**
  6178. * Creates a Viewport object located at (x, y) and sized (width, height).
  6179. */
  6180. function Viewport(x, y, width, height) {
  6181. this.x = x;
  6182. this.y = y;
  6183. this.width = width;
  6184. this.height = height;
  6185. }
  6186. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6187. if (renderWidthOrEngine.getRenderWidth) {
  6188. var engine = renderWidthOrEngine;
  6189. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6190. }
  6191. var renderWidth = renderWidthOrEngine;
  6192. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6193. };
  6194. /**
  6195. * Returns a new Viewport copied from the current one.
  6196. */
  6197. Viewport.prototype.clone = function () {
  6198. return new Viewport(this.x, this.y, this.width, this.height);
  6199. };
  6200. return Viewport;
  6201. }());
  6202. BABYLON.Viewport = Viewport;
  6203. var Frustum = /** @class */ (function () {
  6204. function Frustum() {
  6205. }
  6206. /**
  6207. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6208. */
  6209. Frustum.GetPlanes = function (transform) {
  6210. var frustumPlanes = [];
  6211. for (var index = 0; index < 6; index++) {
  6212. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6213. }
  6214. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6215. return frustumPlanes;
  6216. };
  6217. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6218. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6219. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6220. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6221. frustumPlane.d = transform.m[15] + transform.m[14];
  6222. frustumPlane.normalize();
  6223. };
  6224. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6225. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6226. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6227. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6228. frustumPlane.d = transform.m[15] - transform.m[14];
  6229. frustumPlane.normalize();
  6230. };
  6231. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6232. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6233. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6234. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6235. frustumPlane.d = transform.m[15] + transform.m[12];
  6236. frustumPlane.normalize();
  6237. };
  6238. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6239. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6240. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6241. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6242. frustumPlane.d = transform.m[15] - transform.m[12];
  6243. frustumPlane.normalize();
  6244. };
  6245. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6246. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6247. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6248. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6249. frustumPlane.d = transform.m[15] - transform.m[13];
  6250. frustumPlane.normalize();
  6251. };
  6252. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6253. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6254. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6255. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6256. frustumPlane.d = transform.m[15] + transform.m[13];
  6257. frustumPlane.normalize();
  6258. };
  6259. /**
  6260. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6261. */
  6262. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6263. // Near
  6264. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6265. // Far
  6266. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6267. // Left
  6268. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6269. // Right
  6270. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6271. // Top
  6272. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6273. // Bottom
  6274. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6275. };
  6276. return Frustum;
  6277. }());
  6278. BABYLON.Frustum = Frustum;
  6279. var Space;
  6280. (function (Space) {
  6281. Space[Space["LOCAL"] = 0] = "LOCAL";
  6282. Space[Space["WORLD"] = 1] = "WORLD";
  6283. Space[Space["BONE"] = 2] = "BONE";
  6284. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6285. var Axis = /** @class */ (function () {
  6286. function Axis() {
  6287. }
  6288. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6289. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6290. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6291. return Axis;
  6292. }());
  6293. BABYLON.Axis = Axis;
  6294. ;
  6295. var BezierCurve = /** @class */ (function () {
  6296. function BezierCurve() {
  6297. }
  6298. /**
  6299. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6300. */
  6301. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6302. // Extract X (which is equal to time here)
  6303. var f0 = 1 - 3 * x2 + 3 * x1;
  6304. var f1 = 3 * x2 - 6 * x1;
  6305. var f2 = 3 * x1;
  6306. var refinedT = t;
  6307. for (var i = 0; i < 5; i++) {
  6308. var refinedT2 = refinedT * refinedT;
  6309. var refinedT3 = refinedT2 * refinedT;
  6310. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6311. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6312. refinedT -= (x - t) * slope;
  6313. refinedT = Math.min(1, Math.max(0, refinedT));
  6314. }
  6315. // Resolve cubic bezier for the given x
  6316. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6317. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6318. Math.pow(refinedT, 3);
  6319. };
  6320. return BezierCurve;
  6321. }());
  6322. BABYLON.BezierCurve = BezierCurve;
  6323. var Orientation;
  6324. (function (Orientation) {
  6325. Orientation[Orientation["CW"] = 0] = "CW";
  6326. Orientation[Orientation["CCW"] = 1] = "CCW";
  6327. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6328. var Angle = /** @class */ (function () {
  6329. /**
  6330. * Creates an Angle object of "radians" radians (float).
  6331. */
  6332. function Angle(radians) {
  6333. var _this = this;
  6334. /**
  6335. * Returns the Angle value in degrees (float).
  6336. */
  6337. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6338. /**
  6339. * Returns the Angle value in radians (float).
  6340. */
  6341. this.radians = function () { return _this._radians; };
  6342. this._radians = radians;
  6343. if (this._radians < 0.0)
  6344. this._radians += (2.0 * Math.PI);
  6345. }
  6346. /**
  6347. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6348. */
  6349. Angle.BetweenTwoPoints = function (a, b) {
  6350. var delta = b.subtract(a);
  6351. var theta = Math.atan2(delta.y, delta.x);
  6352. return new Angle(theta);
  6353. };
  6354. /**
  6355. * Returns a new Angle object from the passed float in radians.
  6356. */
  6357. Angle.FromRadians = function (radians) {
  6358. return new Angle(radians);
  6359. };
  6360. /**
  6361. * Returns a new Angle object from the passed float in degrees.
  6362. */
  6363. Angle.FromDegrees = function (degrees) {
  6364. return new Angle(degrees * Math.PI / 180.0);
  6365. };
  6366. return Angle;
  6367. }());
  6368. BABYLON.Angle = Angle;
  6369. var Arc2 = /** @class */ (function () {
  6370. /**
  6371. * Creates an Arc object from the three passed points : start, middle and end.
  6372. */
  6373. function Arc2(startPoint, midPoint, endPoint) {
  6374. this.startPoint = startPoint;
  6375. this.midPoint = midPoint;
  6376. this.endPoint = endPoint;
  6377. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6378. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6379. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6380. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6381. 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);
  6382. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6383. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6384. var a1 = this.startAngle.degrees();
  6385. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6386. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6387. // angles correction
  6388. if (a2 - a1 > +180.0)
  6389. a2 -= 360.0;
  6390. if (a2 - a1 < -180.0)
  6391. a2 += 360.0;
  6392. if (a3 - a2 > +180.0)
  6393. a3 -= 360.0;
  6394. if (a3 - a2 < -180.0)
  6395. a3 += 360.0;
  6396. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6397. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6398. }
  6399. return Arc2;
  6400. }());
  6401. BABYLON.Arc2 = Arc2;
  6402. var Path2 = /** @class */ (function () {
  6403. /**
  6404. * Creates a Path2 object from the starting 2D coordinates x and y.
  6405. */
  6406. function Path2(x, y) {
  6407. this._points = new Array();
  6408. this._length = 0.0;
  6409. this.closed = false;
  6410. this._points.push(new Vector2(x, y));
  6411. }
  6412. /**
  6413. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6414. * Returns the updated Path2.
  6415. */
  6416. Path2.prototype.addLineTo = function (x, y) {
  6417. if (this.closed) {
  6418. return this;
  6419. }
  6420. var newPoint = new Vector2(x, y);
  6421. var previousPoint = this._points[this._points.length - 1];
  6422. this._points.push(newPoint);
  6423. this._length += newPoint.subtract(previousPoint).length();
  6424. return this;
  6425. };
  6426. /**
  6427. * 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.
  6428. * Returns the updated Path2.
  6429. */
  6430. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6431. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6432. if (this.closed) {
  6433. return this;
  6434. }
  6435. var startPoint = this._points[this._points.length - 1];
  6436. var midPoint = new Vector2(midX, midY);
  6437. var endPoint = new Vector2(endX, endY);
  6438. var arc = new Arc2(startPoint, midPoint, endPoint);
  6439. var increment = arc.angle.radians() / numberOfSegments;
  6440. if (arc.orientation === Orientation.CW)
  6441. increment *= -1;
  6442. var currentAngle = arc.startAngle.radians() + increment;
  6443. for (var i = 0; i < numberOfSegments; i++) {
  6444. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6445. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6446. this.addLineTo(x, y);
  6447. currentAngle += increment;
  6448. }
  6449. return this;
  6450. };
  6451. /**
  6452. * Closes the Path2.
  6453. * Returns the Path2.
  6454. */
  6455. Path2.prototype.close = function () {
  6456. this.closed = true;
  6457. return this;
  6458. };
  6459. /**
  6460. * Returns the Path2 total length (float).
  6461. */
  6462. Path2.prototype.length = function () {
  6463. var result = this._length;
  6464. if (!this.closed) {
  6465. var lastPoint = this._points[this._points.length - 1];
  6466. var firstPoint = this._points[0];
  6467. result += (firstPoint.subtract(lastPoint).length());
  6468. }
  6469. return result;
  6470. };
  6471. /**
  6472. * Returns the Path2 internal array of points.
  6473. */
  6474. Path2.prototype.getPoints = function () {
  6475. return this._points;
  6476. };
  6477. /**
  6478. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6479. */
  6480. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6481. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6482. return Vector2.Zero();
  6483. }
  6484. var lengthPosition = normalizedLengthPosition * this.length();
  6485. var previousOffset = 0;
  6486. for (var i = 0; i < this._points.length; i++) {
  6487. var j = (i + 1) % this._points.length;
  6488. var a = this._points[i];
  6489. var b = this._points[j];
  6490. var bToA = b.subtract(a);
  6491. var nextOffset = (bToA.length() + previousOffset);
  6492. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6493. var dir = bToA.normalize();
  6494. var localOffset = lengthPosition - previousOffset;
  6495. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6496. }
  6497. previousOffset = nextOffset;
  6498. }
  6499. return Vector2.Zero();
  6500. };
  6501. /**
  6502. * Returns a new Path2 starting at the coordinates (x, y).
  6503. */
  6504. Path2.StartingAt = function (x, y) {
  6505. return new Path2(x, y);
  6506. };
  6507. return Path2;
  6508. }());
  6509. BABYLON.Path2 = Path2;
  6510. var Path3D = /** @class */ (function () {
  6511. /**
  6512. * new Path3D(path, normal, raw)
  6513. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6514. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6515. * path : an array of Vector3, the curve axis of the Path3D
  6516. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6517. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6518. */
  6519. function Path3D(path, firstNormal, raw) {
  6520. if (firstNormal === void 0) { firstNormal = null; }
  6521. this.path = path;
  6522. this._curve = new Array();
  6523. this._distances = new Array();
  6524. this._tangents = new Array();
  6525. this._normals = new Array();
  6526. this._binormals = new Array();
  6527. for (var p = 0; p < path.length; p++) {
  6528. this._curve[p] = path[p].clone(); // hard copy
  6529. }
  6530. this._raw = raw || false;
  6531. this._compute(firstNormal);
  6532. }
  6533. /**
  6534. * Returns the Path3D array of successive Vector3 designing its curve.
  6535. */
  6536. Path3D.prototype.getCurve = function () {
  6537. return this._curve;
  6538. };
  6539. /**
  6540. * Returns an array populated with tangent vectors on each Path3D curve point.
  6541. */
  6542. Path3D.prototype.getTangents = function () {
  6543. return this._tangents;
  6544. };
  6545. /**
  6546. * Returns an array populated with normal vectors on each Path3D curve point.
  6547. */
  6548. Path3D.prototype.getNormals = function () {
  6549. return this._normals;
  6550. };
  6551. /**
  6552. * Returns an array populated with binormal vectors on each Path3D curve point.
  6553. */
  6554. Path3D.prototype.getBinormals = function () {
  6555. return this._binormals;
  6556. };
  6557. /**
  6558. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6559. */
  6560. Path3D.prototype.getDistances = function () {
  6561. return this._distances;
  6562. };
  6563. /**
  6564. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6565. * Returns the same object updated.
  6566. */
  6567. Path3D.prototype.update = function (path, firstNormal) {
  6568. if (firstNormal === void 0) { firstNormal = null; }
  6569. for (var p = 0; p < path.length; p++) {
  6570. this._curve[p].x = path[p].x;
  6571. this._curve[p].y = path[p].y;
  6572. this._curve[p].z = path[p].z;
  6573. }
  6574. this._compute(firstNormal);
  6575. return this;
  6576. };
  6577. // private function compute() : computes tangents, normals and binormals
  6578. Path3D.prototype._compute = function (firstNormal) {
  6579. var l = this._curve.length;
  6580. // first and last tangents
  6581. this._tangents[0] = this._getFirstNonNullVector(0);
  6582. if (!this._raw) {
  6583. this._tangents[0].normalize();
  6584. }
  6585. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6586. if (!this._raw) {
  6587. this._tangents[l - 1].normalize();
  6588. }
  6589. // normals and binormals at first point : arbitrary vector with _normalVector()
  6590. var tg0 = this._tangents[0];
  6591. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6592. this._normals[0] = pp0;
  6593. if (!this._raw) {
  6594. this._normals[0].normalize();
  6595. }
  6596. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6597. if (!this._raw) {
  6598. this._binormals[0].normalize();
  6599. }
  6600. this._distances[0] = 0.0;
  6601. // normals and binormals : next points
  6602. var prev; // previous vector (segment)
  6603. var cur; // current vector (segment)
  6604. var curTang; // current tangent
  6605. // previous normal
  6606. var prevBinor; // previous binormal
  6607. for (var i = 1; i < l; i++) {
  6608. // tangents
  6609. prev = this._getLastNonNullVector(i);
  6610. if (i < l - 1) {
  6611. cur = this._getFirstNonNullVector(i);
  6612. this._tangents[i] = prev.add(cur);
  6613. this._tangents[i].normalize();
  6614. }
  6615. this._distances[i] = this._distances[i - 1] + prev.length();
  6616. // normals and binormals
  6617. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6618. curTang = this._tangents[i];
  6619. prevBinor = this._binormals[i - 1];
  6620. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6621. if (!this._raw) {
  6622. this._normals[i].normalize();
  6623. }
  6624. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6625. if (!this._raw) {
  6626. this._binormals[i].normalize();
  6627. }
  6628. }
  6629. };
  6630. // private function getFirstNonNullVector(index)
  6631. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6632. Path3D.prototype._getFirstNonNullVector = function (index) {
  6633. var i = 1;
  6634. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6635. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6636. i++;
  6637. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6638. }
  6639. return nNVector;
  6640. };
  6641. // private function getLastNonNullVector(index)
  6642. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6643. Path3D.prototype._getLastNonNullVector = function (index) {
  6644. var i = 1;
  6645. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6646. while (nLVector.length() === 0 && index > i + 1) {
  6647. i++;
  6648. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6649. }
  6650. return nLVector;
  6651. };
  6652. // private function normalVector(v0, vt, va) :
  6653. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6654. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6655. Path3D.prototype._normalVector = function (v0, vt, va) {
  6656. var normal0;
  6657. var tgl = vt.length();
  6658. if (tgl === 0.0) {
  6659. tgl = 1.0;
  6660. }
  6661. if (va === undefined || va === null) {
  6662. var point;
  6663. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6664. point = new Vector3(0.0, -1.0, 0.0);
  6665. }
  6666. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6667. point = new Vector3(1.0, 0.0, 0.0);
  6668. }
  6669. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6670. point = new Vector3(0.0, 0.0, 1.0);
  6671. }
  6672. else {
  6673. point = Vector3.Zero();
  6674. }
  6675. normal0 = Vector3.Cross(vt, point);
  6676. }
  6677. else {
  6678. normal0 = Vector3.Cross(vt, va);
  6679. Vector3.CrossToRef(normal0, vt, normal0);
  6680. }
  6681. normal0.normalize();
  6682. return normal0;
  6683. };
  6684. return Path3D;
  6685. }());
  6686. BABYLON.Path3D = Path3D;
  6687. var Curve3 = /** @class */ (function () {
  6688. /**
  6689. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6690. * A Curve3 is designed from a series of successive Vector3.
  6691. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6692. */
  6693. function Curve3(points) {
  6694. this._length = 0.0;
  6695. this._points = points;
  6696. this._length = this._computeLength(points);
  6697. }
  6698. /**
  6699. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6700. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6701. * @param v1 (Vector3) the control point
  6702. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6703. * @param nbPoints (integer) the wanted number of points in the curve
  6704. */
  6705. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6706. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6707. var bez = new Array();
  6708. var equation = function (t, val0, val1, val2) {
  6709. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6710. return res;
  6711. };
  6712. for (var i = 0; i <= nbPoints; i++) {
  6713. 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)));
  6714. }
  6715. return new Curve3(bez);
  6716. };
  6717. /**
  6718. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6719. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6720. * @param v1 (Vector3) the first control point
  6721. * @param v2 (Vector3) the second control point
  6722. * @param v3 (Vector3) the end point of the Cubic Bezier
  6723. * @param nbPoints (integer) the wanted number of points in the curve
  6724. */
  6725. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6726. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6727. var bez = new Array();
  6728. var equation = function (t, val0, val1, val2, val3) {
  6729. 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;
  6730. return res;
  6731. };
  6732. for (var i = 0; i <= nbPoints; i++) {
  6733. 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)));
  6734. }
  6735. return new Curve3(bez);
  6736. };
  6737. /**
  6738. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6739. * @param p1 (Vector3) the origin point of the Hermite Spline
  6740. * @param t1 (Vector3) the tangent vector at the origin point
  6741. * @param p2 (Vector3) the end point of the Hermite Spline
  6742. * @param t2 (Vector3) the tangent vector at the end point
  6743. * @param nbPoints (integer) the wanted number of points in the curve
  6744. */
  6745. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6746. var hermite = new Array();
  6747. var step = 1.0 / nbPoints;
  6748. for (var i = 0; i <= nbPoints; i++) {
  6749. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6750. }
  6751. return new Curve3(hermite);
  6752. };
  6753. /**
  6754. * Returns a Curve3 object along a CatmullRom Spline curve :
  6755. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6756. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6757. */
  6758. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6759. var totalPoints = new Array();
  6760. totalPoints.push(points[0].clone());
  6761. Array.prototype.push.apply(totalPoints, points);
  6762. totalPoints.push(points[points.length - 1].clone());
  6763. var catmullRom = new Array();
  6764. var step = 1.0 / nbPoints;
  6765. var amount = 0.0;
  6766. for (var i = 0; i < totalPoints.length - 3; i++) {
  6767. amount = 0;
  6768. for (var c = 0; c < nbPoints; c++) {
  6769. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6770. amount += step;
  6771. }
  6772. }
  6773. i--;
  6774. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6775. return new Curve3(catmullRom);
  6776. };
  6777. /**
  6778. * Returns the Curve3 stored array of successive Vector3
  6779. */
  6780. Curve3.prototype.getPoints = function () {
  6781. return this._points;
  6782. };
  6783. /**
  6784. * Returns the computed length (float) of the curve.
  6785. */
  6786. Curve3.prototype.length = function () {
  6787. return this._length;
  6788. };
  6789. /**
  6790. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6791. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6792. * curveA and curveB keep unchanged.
  6793. */
  6794. Curve3.prototype.continue = function (curve) {
  6795. var lastPoint = this._points[this._points.length - 1];
  6796. var continuedPoints = this._points.slice();
  6797. var curvePoints = curve.getPoints();
  6798. for (var i = 1; i < curvePoints.length; i++) {
  6799. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6800. }
  6801. var continuedCurve = new Curve3(continuedPoints);
  6802. return continuedCurve;
  6803. };
  6804. Curve3.prototype._computeLength = function (path) {
  6805. var l = 0;
  6806. for (var i = 1; i < path.length; i++) {
  6807. l += (path[i].subtract(path[i - 1])).length();
  6808. }
  6809. return l;
  6810. };
  6811. return Curve3;
  6812. }());
  6813. BABYLON.Curve3 = Curve3;
  6814. // Vertex formats
  6815. var PositionNormalVertex = /** @class */ (function () {
  6816. function PositionNormalVertex(position, normal) {
  6817. if (position === void 0) { position = Vector3.Zero(); }
  6818. if (normal === void 0) { normal = Vector3.Up(); }
  6819. this.position = position;
  6820. this.normal = normal;
  6821. }
  6822. PositionNormalVertex.prototype.clone = function () {
  6823. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6824. };
  6825. return PositionNormalVertex;
  6826. }());
  6827. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6828. var PositionNormalTextureVertex = /** @class */ (function () {
  6829. function PositionNormalTextureVertex(position, normal, uv) {
  6830. if (position === void 0) { position = Vector3.Zero(); }
  6831. if (normal === void 0) { normal = Vector3.Up(); }
  6832. if (uv === void 0) { uv = Vector2.Zero(); }
  6833. this.position = position;
  6834. this.normal = normal;
  6835. this.uv = uv;
  6836. }
  6837. PositionNormalTextureVertex.prototype.clone = function () {
  6838. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6839. };
  6840. return PositionNormalTextureVertex;
  6841. }());
  6842. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6843. // Temporary pre-allocated objects for engine internal use
  6844. // usage in any internal function :
  6845. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6846. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6847. var Tmp = /** @class */ (function () {
  6848. function Tmp() {
  6849. }
  6850. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6851. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6852. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6853. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6854. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6855. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6856. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6857. Matrix.Zero(), Matrix.Zero(),
  6858. Matrix.Zero(), Matrix.Zero(),
  6859. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6860. return Tmp;
  6861. }());
  6862. BABYLON.Tmp = Tmp;
  6863. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6864. var MathTmp = /** @class */ (function () {
  6865. function MathTmp() {
  6866. }
  6867. MathTmp.Vector3 = [Vector3.Zero()];
  6868. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6869. MathTmp.Quaternion = [Quaternion.Zero()];
  6870. return MathTmp;
  6871. }());
  6872. })(BABYLON || (BABYLON = {}));
  6873. //# sourceMappingURL=babylon.math.js.map
  6874. "use strict";
  6875. var BABYLON;
  6876. (function (BABYLON) {
  6877. var Scalar = /** @class */ (function () {
  6878. function Scalar() {
  6879. }
  6880. /**
  6881. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6882. */
  6883. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6884. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6885. var num = a - b;
  6886. return -epsilon <= num && num <= epsilon;
  6887. };
  6888. /**
  6889. * Returns a string : the upper case translation of the number i to hexadecimal.
  6890. */
  6891. Scalar.ToHex = function (i) {
  6892. var str = i.toString(16);
  6893. if (i <= 15) {
  6894. return ("0" + str).toUpperCase();
  6895. }
  6896. return str.toUpperCase();
  6897. };
  6898. /**
  6899. * Returns -1 if value is negative and +1 is value is positive.
  6900. * Returns the value itself if it's equal to zero.
  6901. */
  6902. Scalar.Sign = function (value) {
  6903. value = +value; // convert to a number
  6904. if (value === 0 || isNaN(value))
  6905. return value;
  6906. return value > 0 ? 1 : -1;
  6907. };
  6908. /**
  6909. * Returns the value itself if it's between min and max.
  6910. * Returns min if the value is lower than min.
  6911. * Returns max if the value is greater than max.
  6912. */
  6913. Scalar.Clamp = function (value, min, max) {
  6914. if (min === void 0) { min = 0; }
  6915. if (max === void 0) { max = 1; }
  6916. return Math.min(max, Math.max(min, value));
  6917. };
  6918. /**
  6919. * Returns the log2 of value.
  6920. */
  6921. Scalar.Log2 = function (value) {
  6922. return Math.log(value) * Math.LOG2E;
  6923. };
  6924. /**
  6925. * Loops the value, so that it is never larger than length and never smaller than 0.
  6926. *
  6927. * This is similar to the modulo operator but it works with floating point numbers.
  6928. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6929. * With t = 5 and length = 2.5, the result would be 0.0.
  6930. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6931. */
  6932. Scalar.Repeat = function (value, length) {
  6933. return value - Math.floor(value / length) * length;
  6934. };
  6935. /**
  6936. * Normalize the value between 0.0 and 1.0 using min and max values
  6937. */
  6938. Scalar.Normalize = function (value, min, max) {
  6939. return (value - min) / (max - min);
  6940. };
  6941. /**
  6942. * Denormalize the value from 0.0 and 1.0 using min and max values
  6943. */
  6944. Scalar.Denormalize = function (normalized, min, max) {
  6945. return (normalized * (max - min) + min);
  6946. };
  6947. /**
  6948. * Calculates the shortest difference between two given angles given in degrees.
  6949. */
  6950. Scalar.DeltaAngle = function (current, target) {
  6951. var num = Scalar.Repeat(target - current, 360.0);
  6952. if (num > 180.0) {
  6953. num -= 360.0;
  6954. }
  6955. return num;
  6956. };
  6957. /**
  6958. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6959. *
  6960. * The returned value will move back and forth between 0 and length
  6961. */
  6962. Scalar.PingPong = function (tx, length) {
  6963. var t = Scalar.Repeat(tx, length * 2.0);
  6964. return length - Math.abs(t - length);
  6965. };
  6966. /**
  6967. * Interpolates between min and max with smoothing at the limits.
  6968. *
  6969. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6970. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6971. */
  6972. Scalar.SmoothStep = function (from, to, tx) {
  6973. var t = Scalar.Clamp(tx);
  6974. t = -2.0 * t * t * t + 3.0 * t * t;
  6975. return to * t + from * (1.0 - t);
  6976. };
  6977. /**
  6978. * Moves a value current towards target.
  6979. *
  6980. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6981. * Negative values of maxDelta pushes the value away from target.
  6982. */
  6983. Scalar.MoveTowards = function (current, target, maxDelta) {
  6984. var result = 0;
  6985. if (Math.abs(target - current) <= maxDelta) {
  6986. result = target;
  6987. }
  6988. else {
  6989. result = current + Scalar.Sign(target - current) * maxDelta;
  6990. }
  6991. return result;
  6992. };
  6993. /**
  6994. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6995. *
  6996. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6997. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6998. */
  6999. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7000. var num = Scalar.DeltaAngle(current, target);
  7001. var result = 0;
  7002. if (-maxDelta < num && num < maxDelta) {
  7003. result = target;
  7004. }
  7005. else {
  7006. target = current + num;
  7007. result = Scalar.MoveTowards(current, target, maxDelta);
  7008. }
  7009. return result;
  7010. };
  7011. /**
  7012. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7013. */
  7014. Scalar.Lerp = function (start, end, amount) {
  7015. return start + ((end - start) * amount);
  7016. };
  7017. /**
  7018. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7019. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7020. */
  7021. Scalar.LerpAngle = function (start, end, amount) {
  7022. var num = Scalar.Repeat(end - start, 360.0);
  7023. if (num > 180.0) {
  7024. num -= 360.0;
  7025. }
  7026. return start + num * Scalar.Clamp(amount);
  7027. };
  7028. /**
  7029. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7030. */
  7031. Scalar.InverseLerp = function (a, b, value) {
  7032. var result = 0;
  7033. if (a != b) {
  7034. result = Scalar.Clamp((value - a) / (b - a));
  7035. }
  7036. else {
  7037. result = 0.0;
  7038. }
  7039. return result;
  7040. };
  7041. /**
  7042. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7043. */
  7044. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7045. var squared = amount * amount;
  7046. var cubed = amount * squared;
  7047. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7048. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7049. var part3 = (cubed - (2.0 * squared)) + amount;
  7050. var part4 = cubed - squared;
  7051. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7052. };
  7053. /**
  7054. * Returns a random float number between and min and max values
  7055. */
  7056. Scalar.RandomRange = function (min, max) {
  7057. if (min === max)
  7058. return min;
  7059. return ((Math.random() * (max - min)) + min);
  7060. };
  7061. /**
  7062. * This function returns percentage of a number in a given range.
  7063. *
  7064. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7065. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7066. */
  7067. Scalar.RangeToPercent = function (number, min, max) {
  7068. return ((number - min) / (max - min));
  7069. };
  7070. /**
  7071. * This function returns number that corresponds to the percentage in a given range.
  7072. *
  7073. * PercentToRange(0.34,0,100) will return 34.
  7074. */
  7075. Scalar.PercentToRange = function (percent, min, max) {
  7076. return ((max - min) * percent + min);
  7077. };
  7078. /**
  7079. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7080. * @param angle The angle to normalize in radian.
  7081. * @return The converted angle.
  7082. */
  7083. Scalar.NormalizeRadians = function (angle) {
  7084. // More precise but slower version kept for reference.
  7085. // angle = angle % Tools.TwoPi;
  7086. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7087. //if (angle > Math.PI) {
  7088. // angle -= Tools.TwoPi;
  7089. //}
  7090. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7091. return angle;
  7092. };
  7093. /**
  7094. * Two pi constants convenient for computation.
  7095. */
  7096. Scalar.TwoPi = Math.PI * 2;
  7097. return Scalar;
  7098. }());
  7099. BABYLON.Scalar = Scalar;
  7100. })(BABYLON || (BABYLON = {}));
  7101. //# sourceMappingURL=babylon.math.scalar.js.map
  7102. "use strict";
  7103. //# sourceMappingURL=babylon.mixins.js.map
  7104. "use strict";
  7105. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7106. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7107. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7108. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7109. //# sourceMappingURL=babylon.webgl2.js.map
  7110. "use strict";
  7111. var BABYLON;
  7112. (function (BABYLON) {
  7113. var __decoratorInitialStore = {};
  7114. var __mergedStore = {};
  7115. var _copySource = function (creationFunction, source, instanciate) {
  7116. var destination = creationFunction();
  7117. // Tags
  7118. if (BABYLON.Tags) {
  7119. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7120. }
  7121. var classStore = getMergedStore(destination);
  7122. // Properties
  7123. for (var property in classStore) {
  7124. var propertyDescriptor = classStore[property];
  7125. var sourceProperty = source[property];
  7126. var propertyType = propertyDescriptor.type;
  7127. if (sourceProperty !== undefined && sourceProperty !== null) {
  7128. switch (propertyType) {
  7129. case 0: // Value
  7130. case 6:// Mesh reference
  7131. destination[property] = sourceProperty;
  7132. break;
  7133. case 1:// Texture
  7134. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7135. break;
  7136. case 2: // Color3
  7137. case 3: // FresnelParameters
  7138. case 4: // Vector2
  7139. case 5: // Vector3
  7140. case 7: // Color Curves
  7141. case 10:// Quaternion
  7142. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7143. break;
  7144. }
  7145. }
  7146. }
  7147. return destination;
  7148. };
  7149. function getDirectStore(target) {
  7150. var classKey = target.getClassName();
  7151. if (!__decoratorInitialStore[classKey]) {
  7152. __decoratorInitialStore[classKey] = {};
  7153. }
  7154. return __decoratorInitialStore[classKey];
  7155. }
  7156. /**
  7157. * Return the list of properties flagged as serializable
  7158. * @param target: host object
  7159. */
  7160. function getMergedStore(target) {
  7161. var classKey = target.getClassName();
  7162. if (__mergedStore[classKey]) {
  7163. return __mergedStore[classKey];
  7164. }
  7165. __mergedStore[classKey] = {};
  7166. var store = __mergedStore[classKey];
  7167. var currentTarget = target;
  7168. var currentKey = classKey;
  7169. while (currentKey) {
  7170. var initialStore = __decoratorInitialStore[currentKey];
  7171. for (var property in initialStore) {
  7172. store[property] = initialStore[property];
  7173. }
  7174. var parent_1 = void 0;
  7175. var done = false;
  7176. do {
  7177. parent_1 = Object.getPrototypeOf(currentTarget);
  7178. if (!parent_1.getClassName) {
  7179. done = true;
  7180. break;
  7181. }
  7182. if (parent_1.getClassName() !== currentKey) {
  7183. break;
  7184. }
  7185. currentTarget = parent_1;
  7186. } while (parent_1);
  7187. if (done) {
  7188. break;
  7189. }
  7190. currentKey = parent_1.getClassName();
  7191. currentTarget = parent_1;
  7192. }
  7193. return store;
  7194. }
  7195. function generateSerializableMember(type, sourceName) {
  7196. return function (target, propertyKey) {
  7197. var classStore = getDirectStore(target);
  7198. if (!classStore[propertyKey]) {
  7199. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7200. }
  7201. };
  7202. }
  7203. function generateExpandMember(setCallback, targetKey) {
  7204. if (targetKey === void 0) { targetKey = null; }
  7205. return function (target, propertyKey) {
  7206. var key = targetKey || ("_" + propertyKey);
  7207. Object.defineProperty(target, propertyKey, {
  7208. get: function () {
  7209. return this[key];
  7210. },
  7211. set: function (value) {
  7212. if (this[key] === value) {
  7213. return;
  7214. }
  7215. this[key] = value;
  7216. target[setCallback].apply(this);
  7217. },
  7218. enumerable: true,
  7219. configurable: true
  7220. });
  7221. };
  7222. }
  7223. function expandToProperty(callback, targetKey) {
  7224. if (targetKey === void 0) { targetKey = null; }
  7225. return generateExpandMember(callback, targetKey);
  7226. }
  7227. BABYLON.expandToProperty = expandToProperty;
  7228. function serialize(sourceName) {
  7229. return generateSerializableMember(0, sourceName); // value member
  7230. }
  7231. BABYLON.serialize = serialize;
  7232. function serializeAsTexture(sourceName) {
  7233. return generateSerializableMember(1, sourceName); // texture member
  7234. }
  7235. BABYLON.serializeAsTexture = serializeAsTexture;
  7236. function serializeAsColor3(sourceName) {
  7237. return generateSerializableMember(2, sourceName); // color3 member
  7238. }
  7239. BABYLON.serializeAsColor3 = serializeAsColor3;
  7240. function serializeAsFresnelParameters(sourceName) {
  7241. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7242. }
  7243. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7244. function serializeAsVector2(sourceName) {
  7245. return generateSerializableMember(4, sourceName); // vector2 member
  7246. }
  7247. BABYLON.serializeAsVector2 = serializeAsVector2;
  7248. function serializeAsVector3(sourceName) {
  7249. return generateSerializableMember(5, sourceName); // vector3 member
  7250. }
  7251. BABYLON.serializeAsVector3 = serializeAsVector3;
  7252. function serializeAsMeshReference(sourceName) {
  7253. return generateSerializableMember(6, sourceName); // mesh reference member
  7254. }
  7255. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7256. function serializeAsColorCurves(sourceName) {
  7257. return generateSerializableMember(7, sourceName); // color curves
  7258. }
  7259. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7260. function serializeAsColor4(sourceName) {
  7261. return generateSerializableMember(8, sourceName); // color 4
  7262. }
  7263. BABYLON.serializeAsColor4 = serializeAsColor4;
  7264. function serializeAsImageProcessingConfiguration(sourceName) {
  7265. return generateSerializableMember(9, sourceName); // image processing
  7266. }
  7267. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7268. function serializeAsQuaternion(sourceName) {
  7269. return generateSerializableMember(10, sourceName); // quaternion member
  7270. }
  7271. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7272. var SerializationHelper = /** @class */ (function () {
  7273. function SerializationHelper() {
  7274. }
  7275. SerializationHelper.Serialize = function (entity, serializationObject) {
  7276. if (!serializationObject) {
  7277. serializationObject = {};
  7278. }
  7279. // Tags
  7280. if (BABYLON.Tags) {
  7281. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7282. }
  7283. var serializedProperties = getMergedStore(entity);
  7284. // Properties
  7285. for (var property in serializedProperties) {
  7286. var propertyDescriptor = serializedProperties[property];
  7287. var targetPropertyName = propertyDescriptor.sourceName || property;
  7288. var propertyType = propertyDescriptor.type;
  7289. var sourceProperty = entity[property];
  7290. if (sourceProperty !== undefined && sourceProperty !== null) {
  7291. switch (propertyType) {
  7292. case 0:// Value
  7293. serializationObject[targetPropertyName] = sourceProperty;
  7294. break;
  7295. case 1:// Texture
  7296. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7297. break;
  7298. case 2:// Color3
  7299. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7300. break;
  7301. case 3:// FresnelParameters
  7302. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7303. break;
  7304. case 4:// Vector2
  7305. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7306. break;
  7307. case 5:// Vector3
  7308. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7309. break;
  7310. case 6:// Mesh reference
  7311. serializationObject[targetPropertyName] = sourceProperty.id;
  7312. break;
  7313. case 7:// Color Curves
  7314. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7315. break;
  7316. case 8:// Color 4
  7317. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7318. break;
  7319. case 9:// Image Processing
  7320. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7321. break;
  7322. }
  7323. }
  7324. }
  7325. return serializationObject;
  7326. };
  7327. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7328. if (rootUrl === void 0) { rootUrl = null; }
  7329. var destination = creationFunction();
  7330. if (!rootUrl) {
  7331. rootUrl = "";
  7332. }
  7333. // Tags
  7334. if (BABYLON.Tags) {
  7335. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7336. }
  7337. var classStore = getMergedStore(destination);
  7338. // Properties
  7339. for (var property in classStore) {
  7340. var propertyDescriptor = classStore[property];
  7341. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7342. var propertyType = propertyDescriptor.type;
  7343. if (sourceProperty !== undefined && sourceProperty !== null) {
  7344. var dest = destination;
  7345. switch (propertyType) {
  7346. case 0:// Value
  7347. dest[property] = sourceProperty;
  7348. break;
  7349. case 1:// Texture
  7350. if (scene) {
  7351. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7352. }
  7353. break;
  7354. case 2:// Color3
  7355. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7356. break;
  7357. case 3:// FresnelParameters
  7358. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7359. break;
  7360. case 4:// Vector2
  7361. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7362. break;
  7363. case 5:// Vector3
  7364. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7365. break;
  7366. case 6:// Mesh reference
  7367. if (scene) {
  7368. dest[property] = scene.getLastMeshByID(sourceProperty);
  7369. }
  7370. break;
  7371. case 7:// Color Curves
  7372. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7373. break;
  7374. case 8:// Color 4
  7375. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7376. break;
  7377. case 9:// Image Processing
  7378. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7379. break;
  7380. }
  7381. }
  7382. }
  7383. return destination;
  7384. };
  7385. SerializationHelper.Clone = function (creationFunction, source) {
  7386. return _copySource(creationFunction, source, false);
  7387. };
  7388. SerializationHelper.Instanciate = function (creationFunction, source) {
  7389. return _copySource(creationFunction, source, true);
  7390. };
  7391. return SerializationHelper;
  7392. }());
  7393. BABYLON.SerializationHelper = SerializationHelper;
  7394. })(BABYLON || (BABYLON = {}));
  7395. //# sourceMappingURL=babylon.decorators.js.map
  7396. "use strict";
  7397. var BABYLON;
  7398. (function (BABYLON) {
  7399. /**
  7400. * Wrapper class for promise with external resolve and reject.
  7401. */
  7402. var Deferred = /** @class */ (function () {
  7403. /**
  7404. * Constructor for this deferred object.
  7405. */
  7406. function Deferred() {
  7407. var _this = this;
  7408. this.promise = new Promise(function (resolve, reject) {
  7409. _this._resolve = resolve;
  7410. _this._reject = reject;
  7411. });
  7412. }
  7413. Object.defineProperty(Deferred.prototype, "resolve", {
  7414. /**
  7415. * The resolve method of the promise associated with this deferred object.
  7416. */
  7417. get: function () {
  7418. return this._resolve;
  7419. },
  7420. enumerable: true,
  7421. configurable: true
  7422. });
  7423. Object.defineProperty(Deferred.prototype, "reject", {
  7424. /**
  7425. * The reject method of the promise associated with this deferred object.
  7426. */
  7427. get: function () {
  7428. return this._reject;
  7429. },
  7430. enumerable: true,
  7431. configurable: true
  7432. });
  7433. return Deferred;
  7434. }());
  7435. BABYLON.Deferred = Deferred;
  7436. })(BABYLON || (BABYLON = {}));
  7437. //# sourceMappingURL=babylon.deferred.js.map
  7438. "use strict";
  7439. var BABYLON;
  7440. (function (BABYLON) {
  7441. /**
  7442. * A class serves as a medium between the observable and its observers
  7443. */
  7444. var EventState = /** @class */ (function () {
  7445. /**
  7446. * Create a new EventState
  7447. * @param mask defines the mask associated with this state
  7448. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7449. * @param target defines the original target of the state
  7450. * @param currentTarget defines the current target of the state
  7451. */
  7452. function EventState(mask, skipNextObservers, target, currentTarget) {
  7453. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7454. this.initalize(mask, skipNextObservers, target, currentTarget);
  7455. }
  7456. /**
  7457. * Initialize the current event state
  7458. * @param mask defines the mask associated with this state
  7459. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7460. * @param target defines the original target of the state
  7461. * @param currentTarget defines the current target of the state
  7462. * @returns the current event state
  7463. */
  7464. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7465. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7466. this.mask = mask;
  7467. this.skipNextObservers = skipNextObservers;
  7468. this.target = target;
  7469. this.currentTarget = currentTarget;
  7470. return this;
  7471. };
  7472. return EventState;
  7473. }());
  7474. BABYLON.EventState = EventState;
  7475. /**
  7476. * Represent an Observer registered to a given Observable object.
  7477. */
  7478. var Observer = /** @class */ (function () {
  7479. /**
  7480. * Creates a new observer
  7481. * @param callback defines the callback to call when the observer is notified
  7482. * @param mask defines the mask of the observer (used to filter notifications)
  7483. * @param scope defines the current scope used to restore the JS context
  7484. */
  7485. function Observer(
  7486. /**
  7487. * Defines the callback to call when the observer is notified
  7488. */
  7489. callback,
  7490. /**
  7491. * Defines the mask of the observer (used to filter notifications)
  7492. */
  7493. mask,
  7494. /**
  7495. * Defines the current scope used to restore the JS context
  7496. */
  7497. scope) {
  7498. if (scope === void 0) { scope = null; }
  7499. this.callback = callback;
  7500. this.mask = mask;
  7501. this.scope = scope;
  7502. /** @ignore */
  7503. this._willBeUnregistered = false;
  7504. /**
  7505. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7506. */
  7507. this.unregisterOnNextCall = false;
  7508. }
  7509. return Observer;
  7510. }());
  7511. BABYLON.Observer = Observer;
  7512. /**
  7513. * Represent a list of observers registered to multiple Observables object.
  7514. */
  7515. var MultiObserver = /** @class */ (function () {
  7516. function MultiObserver() {
  7517. }
  7518. /**
  7519. * Release associated resources
  7520. */
  7521. MultiObserver.prototype.dispose = function () {
  7522. if (this._observers && this._observables) {
  7523. for (var index = 0; index < this._observers.length; index++) {
  7524. this._observables[index].remove(this._observers[index]);
  7525. }
  7526. }
  7527. this._observers = null;
  7528. this._observables = null;
  7529. };
  7530. /**
  7531. * Raise a callback when one of the observable will notify
  7532. * @param observables defines a list of observables to watch
  7533. * @param callback defines the callback to call on notification
  7534. * @param mask defines the mask used to filter notifications
  7535. * @param scope defines the current scope used to restore the JS context
  7536. * @returns the new MultiObserver
  7537. */
  7538. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7539. if (mask === void 0) { mask = -1; }
  7540. if (scope === void 0) { scope = null; }
  7541. var result = new MultiObserver();
  7542. result._observers = new Array();
  7543. result._observables = observables;
  7544. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7545. var observable = observables_1[_i];
  7546. var observer = observable.add(callback, mask, false, scope);
  7547. if (observer) {
  7548. result._observers.push(observer);
  7549. }
  7550. }
  7551. return result;
  7552. };
  7553. return MultiObserver;
  7554. }());
  7555. BABYLON.MultiObserver = MultiObserver;
  7556. /**
  7557. * The Observable class is a simple implementation of the Observable pattern.
  7558. * 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.
  7559. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7560. * 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).
  7561. * 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.
  7562. */
  7563. var Observable = /** @class */ (function () {
  7564. /**
  7565. * Creates a new observable
  7566. * @param onObserverAdded defines a callback to call when a new observer is added
  7567. */
  7568. function Observable(onObserverAdded) {
  7569. this._observers = new Array();
  7570. this._eventState = new EventState(0);
  7571. if (onObserverAdded) {
  7572. this._onObserverAdded = onObserverAdded;
  7573. }
  7574. }
  7575. /**
  7576. * Create a new Observer with the specified callback
  7577. * @param callback the callback that will be executed for that Observer
  7578. * @param mask the mask used to filter observers
  7579. * @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.
  7580. * @param scope optional scope for the callback to be called from
  7581. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7582. * @returns the new observer created for the callback
  7583. */
  7584. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7585. if (mask === void 0) { mask = -1; }
  7586. if (insertFirst === void 0) { insertFirst = false; }
  7587. if (scope === void 0) { scope = null; }
  7588. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7589. if (!callback) {
  7590. return null;
  7591. }
  7592. var observer = new Observer(callback, mask, scope);
  7593. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7594. if (insertFirst) {
  7595. this._observers.unshift(observer);
  7596. }
  7597. else {
  7598. this._observers.push(observer);
  7599. }
  7600. if (this._onObserverAdded) {
  7601. this._onObserverAdded(observer);
  7602. }
  7603. return observer;
  7604. };
  7605. /**
  7606. * Remove an Observer from the Observable object
  7607. * @param observer the instance of the Observer to remove
  7608. * @returns false if it doesn't belong to this Observable
  7609. */
  7610. Observable.prototype.remove = function (observer) {
  7611. if (!observer) {
  7612. return false;
  7613. }
  7614. var index = this._observers.indexOf(observer);
  7615. if (index !== -1) {
  7616. this._observers.splice(index, 1);
  7617. return true;
  7618. }
  7619. return false;
  7620. };
  7621. /**
  7622. * Remove a callback from the Observable object
  7623. * @param callback the callback to remove
  7624. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7625. * @returns false if it doesn't belong to this Observable
  7626. */
  7627. Observable.prototype.removeCallback = function (callback, scope) {
  7628. for (var index = 0; index < this._observers.length; index++) {
  7629. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7630. this._observers.splice(index, 1);
  7631. return true;
  7632. }
  7633. }
  7634. return false;
  7635. };
  7636. Observable.prototype._deferUnregister = function (observer) {
  7637. var _this = this;
  7638. observer.unregisterOnNextCall = false;
  7639. observer._willBeUnregistered = true;
  7640. BABYLON.Tools.SetImmediate(function () {
  7641. _this.remove(observer);
  7642. });
  7643. };
  7644. /**
  7645. * Notify all Observers by calling their respective callback with the given data
  7646. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7647. * @param eventData defines the data to send to all observers
  7648. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7649. * @param target defines the original target of the state
  7650. * @param currentTarget defines the current target of the state
  7651. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7652. */
  7653. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7654. if (mask === void 0) { mask = -1; }
  7655. if (!this._observers.length) {
  7656. return true;
  7657. }
  7658. var state = this._eventState;
  7659. state.mask = mask;
  7660. state.target = target;
  7661. state.currentTarget = currentTarget;
  7662. state.skipNextObservers = false;
  7663. state.lastReturnValue = eventData;
  7664. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7665. var obs = _a[_i];
  7666. if (obs._willBeUnregistered) {
  7667. continue;
  7668. }
  7669. if (obs.mask & mask) {
  7670. if (obs.scope) {
  7671. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7672. }
  7673. else {
  7674. state.lastReturnValue = obs.callback(eventData, state);
  7675. }
  7676. if (obs.unregisterOnNextCall) {
  7677. this._deferUnregister(obs);
  7678. }
  7679. }
  7680. if (state.skipNextObservers) {
  7681. return false;
  7682. }
  7683. }
  7684. return true;
  7685. };
  7686. /**
  7687. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7688. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7689. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7690. * and it is crucial that all callbacks will be executed.
  7691. * The order of the callbacks is kept, callbacks are not executed parallel.
  7692. *
  7693. * @param eventData The data to be sent to each callback
  7694. * @param mask is used to filter observers defaults to -1
  7695. * @param target defines the callback target (see EventState)
  7696. * @param currentTarget defines he current object in the bubbling phase
  7697. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7698. */
  7699. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7700. var _this = this;
  7701. if (mask === void 0) { mask = -1; }
  7702. // create an empty promise
  7703. var p = Promise.resolve(eventData);
  7704. // no observers? return this promise.
  7705. if (!this._observers.length) {
  7706. return p;
  7707. }
  7708. var state = this._eventState;
  7709. state.mask = mask;
  7710. state.target = target;
  7711. state.currentTarget = currentTarget;
  7712. state.skipNextObservers = false;
  7713. // execute one callback after another (not using Promise.all, the order is important)
  7714. this._observers.forEach(function (obs) {
  7715. if (state.skipNextObservers) {
  7716. return;
  7717. }
  7718. if (obs._willBeUnregistered) {
  7719. return;
  7720. }
  7721. if (obs.mask & mask) {
  7722. if (obs.scope) {
  7723. p = p.then(function (lastReturnedValue) {
  7724. state.lastReturnValue = lastReturnedValue;
  7725. return obs.callback.apply(obs.scope, [eventData, state]);
  7726. });
  7727. }
  7728. else {
  7729. p = p.then(function (lastReturnedValue) {
  7730. state.lastReturnValue = lastReturnedValue;
  7731. return obs.callback(eventData, state);
  7732. });
  7733. }
  7734. if (obs.unregisterOnNextCall) {
  7735. _this._deferUnregister(obs);
  7736. }
  7737. }
  7738. });
  7739. // return the eventData
  7740. return p.then(function () { return eventData; });
  7741. };
  7742. /**
  7743. * Notify a specific observer
  7744. * @param observer defines the observer to notify
  7745. * @param eventData defines the data to be sent to each callback
  7746. * @param mask is used to filter observers defaults to -1
  7747. */
  7748. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7749. if (mask === void 0) { mask = -1; }
  7750. var state = this._eventState;
  7751. state.mask = mask;
  7752. state.skipNextObservers = false;
  7753. observer.callback(eventData, state);
  7754. };
  7755. /**
  7756. * Gets a boolean indicating if the observable has at least one observer
  7757. * @returns true is the Observable has at least one Observer registered
  7758. */
  7759. Observable.prototype.hasObservers = function () {
  7760. return this._observers.length > 0;
  7761. };
  7762. /**
  7763. * Clear the list of observers
  7764. */
  7765. Observable.prototype.clear = function () {
  7766. this._observers = new Array();
  7767. this._onObserverAdded = null;
  7768. };
  7769. /**
  7770. * Clone the current observable
  7771. * @returns a new observable
  7772. */
  7773. Observable.prototype.clone = function () {
  7774. var result = new Observable();
  7775. result._observers = this._observers.slice(0);
  7776. return result;
  7777. };
  7778. /**
  7779. * Does this observable handles observer registered with a given mask
  7780. * @param mask defines the mask to be tested
  7781. * @return whether or not one observer registered with the given mask is handeled
  7782. **/
  7783. Observable.prototype.hasSpecificMask = function (mask) {
  7784. if (mask === void 0) { mask = -1; }
  7785. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7786. var obs = _a[_i];
  7787. if (obs.mask & mask || obs.mask === mask) {
  7788. return true;
  7789. }
  7790. }
  7791. return false;
  7792. };
  7793. return Observable;
  7794. }());
  7795. BABYLON.Observable = Observable;
  7796. })(BABYLON || (BABYLON = {}));
  7797. //# sourceMappingURL=babylon.observable.js.map
  7798. "use strict";
  7799. var BABYLON;
  7800. (function (BABYLON) {
  7801. var SmartArray = /** @class */ (function () {
  7802. function SmartArray(capacity) {
  7803. this.length = 0;
  7804. this.data = new Array(capacity);
  7805. this._id = SmartArray._GlobalId++;
  7806. }
  7807. SmartArray.prototype.push = function (value) {
  7808. this.data[this.length++] = value;
  7809. if (this.length > this.data.length) {
  7810. this.data.length *= 2;
  7811. }
  7812. };
  7813. SmartArray.prototype.forEach = function (func) {
  7814. for (var index = 0; index < this.length; index++) {
  7815. func(this.data[index]);
  7816. }
  7817. };
  7818. SmartArray.prototype.sort = function (compareFn) {
  7819. this.data.sort(compareFn);
  7820. };
  7821. SmartArray.prototype.reset = function () {
  7822. this.length = 0;
  7823. };
  7824. SmartArray.prototype.dispose = function () {
  7825. this.reset();
  7826. if (this.data) {
  7827. this.data.length = 0;
  7828. this.data = [];
  7829. }
  7830. };
  7831. SmartArray.prototype.concat = function (array) {
  7832. if (array.length === 0) {
  7833. return;
  7834. }
  7835. if (this.length + array.length > this.data.length) {
  7836. this.data.length = (this.length + array.length) * 2;
  7837. }
  7838. for (var index = 0; index < array.length; index++) {
  7839. this.data[this.length++] = (array.data || array)[index];
  7840. }
  7841. };
  7842. SmartArray.prototype.indexOf = function (value) {
  7843. var position = this.data.indexOf(value);
  7844. if (position >= this.length) {
  7845. return -1;
  7846. }
  7847. return position;
  7848. };
  7849. SmartArray.prototype.contains = function (value) {
  7850. return this.data.indexOf(value) !== -1;
  7851. };
  7852. // Statics
  7853. SmartArray._GlobalId = 0;
  7854. return SmartArray;
  7855. }());
  7856. BABYLON.SmartArray = SmartArray;
  7857. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7858. __extends(SmartArrayNoDuplicate, _super);
  7859. function SmartArrayNoDuplicate() {
  7860. var _this = _super !== null && _super.apply(this, arguments) || this;
  7861. _this._duplicateId = 0;
  7862. return _this;
  7863. }
  7864. SmartArrayNoDuplicate.prototype.push = function (value) {
  7865. _super.prototype.push.call(this, value);
  7866. if (!value.__smartArrayFlags) {
  7867. value.__smartArrayFlags = {};
  7868. }
  7869. value.__smartArrayFlags[this._id] = this._duplicateId;
  7870. };
  7871. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7872. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7873. return false;
  7874. }
  7875. this.push(value);
  7876. return true;
  7877. };
  7878. SmartArrayNoDuplicate.prototype.reset = function () {
  7879. _super.prototype.reset.call(this);
  7880. this._duplicateId++;
  7881. };
  7882. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7883. if (array.length === 0) {
  7884. return;
  7885. }
  7886. if (this.length + array.length > this.data.length) {
  7887. this.data.length = (this.length + array.length) * 2;
  7888. }
  7889. for (var index = 0; index < array.length; index++) {
  7890. var item = (array.data || array)[index];
  7891. this.pushNoDuplicate(item);
  7892. }
  7893. };
  7894. return SmartArrayNoDuplicate;
  7895. }(SmartArray));
  7896. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7897. })(BABYLON || (BABYLON = {}));
  7898. //# sourceMappingURL=babylon.smartArray.js.map
  7899. "use strict";
  7900. var BABYLON;
  7901. (function (BABYLON) {
  7902. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7903. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7904. var LoadFileError = /** @class */ (function (_super) {
  7905. __extends(LoadFileError, _super);
  7906. function LoadFileError(message, request) {
  7907. var _this = _super.call(this, message) || this;
  7908. _this.request = request;
  7909. _this.name = "LoadFileError";
  7910. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7911. return _this;
  7912. }
  7913. // Polyfill for Object.setPrototypeOf if necessary.
  7914. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7915. return LoadFileError;
  7916. }(Error));
  7917. BABYLON.LoadFileError = LoadFileError;
  7918. var RetryStrategy = /** @class */ (function () {
  7919. function RetryStrategy() {
  7920. }
  7921. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7922. if (maxRetries === void 0) { maxRetries = 3; }
  7923. if (baseInterval === void 0) { baseInterval = 500; }
  7924. return function (url, request, retryIndex) {
  7925. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7926. return -1;
  7927. }
  7928. return Math.pow(2, retryIndex) * baseInterval;
  7929. };
  7930. };
  7931. return RetryStrategy;
  7932. }());
  7933. BABYLON.RetryStrategy = RetryStrategy;
  7934. // Screenshots
  7935. var screenshotCanvas;
  7936. var cloneValue = function (source, destinationObject) {
  7937. if (!source)
  7938. return null;
  7939. if (source instanceof BABYLON.Mesh) {
  7940. return null;
  7941. }
  7942. if (source instanceof BABYLON.SubMesh) {
  7943. return source.clone(destinationObject);
  7944. }
  7945. else if (source.clone) {
  7946. return source.clone();
  7947. }
  7948. return null;
  7949. };
  7950. var Tools = /** @class */ (function () {
  7951. function Tools() {
  7952. }
  7953. /**
  7954. * Interpolates between a and b via alpha
  7955. * @param a The lower value (returned when alpha = 0)
  7956. * @param b The upper value (returned when alpha = 1)
  7957. * @param alpha The interpolation-factor
  7958. * @return The mixed value
  7959. */
  7960. Tools.Mix = function (a, b, alpha) {
  7961. return a * (1 - alpha) + b * alpha;
  7962. };
  7963. Tools.Instantiate = function (className) {
  7964. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7965. return Tools.RegisteredExternalClasses[className];
  7966. }
  7967. var arr = className.split(".");
  7968. var fn = (window || this);
  7969. for (var i = 0, len = arr.length; i < len; i++) {
  7970. fn = fn[arr[i]];
  7971. }
  7972. if (typeof fn !== "function") {
  7973. return null;
  7974. }
  7975. return fn;
  7976. };
  7977. /**
  7978. * Provides a slice function that will work even on IE
  7979. * @param data defines the array to slice
  7980. * @returns the new sliced array
  7981. */
  7982. Tools.Slice = function (data) {
  7983. if (data.slice) {
  7984. return data.slice();
  7985. }
  7986. return Array.prototype.slice.call(data);
  7987. };
  7988. Tools.SetImmediate = function (action) {
  7989. if (window.setImmediate) {
  7990. window.setImmediate(action);
  7991. }
  7992. else {
  7993. setTimeout(action, 1);
  7994. }
  7995. };
  7996. Tools.IsExponentOfTwo = function (value) {
  7997. var count = 1;
  7998. do {
  7999. count *= 2;
  8000. } while (count < value);
  8001. return count === value;
  8002. };
  8003. /**
  8004. * Find the next highest power of two.
  8005. * @param x Number to start search from.
  8006. * @return Next highest power of two.
  8007. */
  8008. Tools.CeilingPOT = function (x) {
  8009. x--;
  8010. x |= x >> 1;
  8011. x |= x >> 2;
  8012. x |= x >> 4;
  8013. x |= x >> 8;
  8014. x |= x >> 16;
  8015. x++;
  8016. return x;
  8017. };
  8018. /**
  8019. * Find the next lowest power of two.
  8020. * @param x Number to start search from.
  8021. * @return Next lowest power of two.
  8022. */
  8023. Tools.FloorPOT = function (x) {
  8024. x = x | (x >> 1);
  8025. x = x | (x >> 2);
  8026. x = x | (x >> 4);
  8027. x = x | (x >> 8);
  8028. x = x | (x >> 16);
  8029. return x - (x >> 1);
  8030. };
  8031. /**
  8032. * Find the nearest power of two.
  8033. * @param x Number to start search from.
  8034. * @return Next nearest power of two.
  8035. */
  8036. Tools.NearestPOT = function (x) {
  8037. var c = Tools.CeilingPOT(x);
  8038. var f = Tools.FloorPOT(x);
  8039. return (c - x) > (x - f) ? f : c;
  8040. };
  8041. Tools.GetExponentOfTwo = function (value, max, mode) {
  8042. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8043. var pot;
  8044. switch (mode) {
  8045. case BABYLON.Engine.SCALEMODE_FLOOR:
  8046. pot = Tools.FloorPOT(value);
  8047. break;
  8048. case BABYLON.Engine.SCALEMODE_NEAREST:
  8049. pot = Tools.NearestPOT(value);
  8050. break;
  8051. case BABYLON.Engine.SCALEMODE_CEILING:
  8052. default:
  8053. pot = Tools.CeilingPOT(value);
  8054. break;
  8055. }
  8056. return Math.min(pot, max);
  8057. };
  8058. Tools.GetFilename = function (path) {
  8059. var index = path.lastIndexOf("/");
  8060. if (index < 0)
  8061. return path;
  8062. return path.substring(index + 1);
  8063. };
  8064. /**
  8065. * Extracts the "folder" part of a path (everything before the filename).
  8066. * @param uri The URI to extract the info from
  8067. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8068. * @returns The "folder" part of the path
  8069. */
  8070. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8071. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8072. var index = uri.lastIndexOf("/");
  8073. if (index < 0) {
  8074. if (returnUnchangedIfNoSlash) {
  8075. return uri;
  8076. }
  8077. return "";
  8078. }
  8079. return uri.substring(0, index + 1);
  8080. };
  8081. Tools.GetDOMTextContent = function (element) {
  8082. var result = "";
  8083. var child = element.firstChild;
  8084. while (child) {
  8085. if (child.nodeType === 3) {
  8086. result += child.textContent;
  8087. }
  8088. child = child.nextSibling;
  8089. }
  8090. return result;
  8091. };
  8092. Tools.ToDegrees = function (angle) {
  8093. return angle * 180 / Math.PI;
  8094. };
  8095. Tools.ToRadians = function (angle) {
  8096. return angle * Math.PI / 180;
  8097. };
  8098. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8099. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8100. var output = "";
  8101. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8102. var i = 0;
  8103. var bytes = new Uint8Array(buffer);
  8104. while (i < bytes.length) {
  8105. chr1 = bytes[i++];
  8106. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8107. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8108. enc1 = chr1 >> 2;
  8109. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8110. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8111. enc4 = chr3 & 63;
  8112. if (isNaN(chr2)) {
  8113. enc3 = enc4 = 64;
  8114. }
  8115. else if (isNaN(chr3)) {
  8116. enc4 = 64;
  8117. }
  8118. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8119. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8120. }
  8121. return "data:image/png;base64," + output;
  8122. };
  8123. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8124. if (bias === void 0) { bias = null; }
  8125. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8126. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8127. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8128. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8129. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8130. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8131. }
  8132. if (bias) {
  8133. minimum.x -= minimum.x * bias.x + bias.y;
  8134. minimum.y -= minimum.y * bias.x + bias.y;
  8135. minimum.z -= minimum.z * bias.x + bias.y;
  8136. maximum.x += maximum.x * bias.x + bias.y;
  8137. maximum.y += maximum.y * bias.x + bias.y;
  8138. maximum.z += maximum.z * bias.x + bias.y;
  8139. }
  8140. return {
  8141. minimum: minimum,
  8142. maximum: maximum
  8143. };
  8144. };
  8145. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8146. if (bias === void 0) { bias = null; }
  8147. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8148. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8149. if (!stride) {
  8150. stride = 3;
  8151. }
  8152. for (var index = start; index < start + count; index++) {
  8153. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8154. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8155. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8156. }
  8157. if (bias) {
  8158. minimum.x -= minimum.x * bias.x + bias.y;
  8159. minimum.y -= minimum.y * bias.x + bias.y;
  8160. minimum.z -= minimum.z * bias.x + bias.y;
  8161. maximum.x += maximum.x * bias.x + bias.y;
  8162. maximum.y += maximum.y * bias.x + bias.y;
  8163. maximum.z += maximum.z * bias.x + bias.y;
  8164. }
  8165. return {
  8166. minimum: minimum,
  8167. maximum: maximum
  8168. };
  8169. };
  8170. Tools.Vector2ArrayFeeder = function (array) {
  8171. return function (index) {
  8172. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8173. var length = isFloatArray ? array.length / 2 : array.length;
  8174. if (index >= length) {
  8175. return null;
  8176. }
  8177. if (isFloatArray) {
  8178. var fa = array;
  8179. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8180. }
  8181. var a = array;
  8182. return a[index];
  8183. };
  8184. };
  8185. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8186. if (bias === void 0) { bias = null; }
  8187. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8188. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8189. var i = 0;
  8190. var cur = feeder(i++);
  8191. while (cur) {
  8192. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8193. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8194. cur = feeder(i++);
  8195. }
  8196. if (bias) {
  8197. minimum.x -= minimum.x * bias.x + bias.y;
  8198. minimum.y -= minimum.y * bias.x + bias.y;
  8199. maximum.x += maximum.x * bias.x + bias.y;
  8200. maximum.y += maximum.y * bias.x + bias.y;
  8201. }
  8202. return {
  8203. minimum: minimum,
  8204. maximum: maximum
  8205. };
  8206. };
  8207. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8208. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8209. return null;
  8210. return Array.isArray(obj) ? obj : [obj];
  8211. };
  8212. // Misc.
  8213. Tools.GetPointerPrefix = function () {
  8214. var eventPrefix = "pointer";
  8215. // Check if pointer events are supported
  8216. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8217. eventPrefix = "mouse";
  8218. }
  8219. return eventPrefix;
  8220. };
  8221. /**
  8222. * @param func - the function to be called
  8223. * @param requester - the object that will request the next frame. Falls back to window.
  8224. */
  8225. Tools.QueueNewFrame = function (func, requester) {
  8226. if (!Tools.IsWindowObjectExist()) {
  8227. return setTimeout(func, 16);
  8228. }
  8229. if (!requester) {
  8230. requester = window;
  8231. }
  8232. if (requester.requestAnimationFrame) {
  8233. return requester.requestAnimationFrame(func);
  8234. }
  8235. else if (requester.msRequestAnimationFrame) {
  8236. return requester.msRequestAnimationFrame(func);
  8237. }
  8238. else if (requester.webkitRequestAnimationFrame) {
  8239. return requester.webkitRequestAnimationFrame(func);
  8240. }
  8241. else if (requester.mozRequestAnimationFrame) {
  8242. return requester.mozRequestAnimationFrame(func);
  8243. }
  8244. else if (requester.oRequestAnimationFrame) {
  8245. return requester.oRequestAnimationFrame(func);
  8246. }
  8247. else {
  8248. return window.setTimeout(func, 16);
  8249. }
  8250. };
  8251. Tools.RequestFullscreen = function (element) {
  8252. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8253. if (!requestFunction)
  8254. return;
  8255. requestFunction.call(element);
  8256. };
  8257. Tools.ExitFullscreen = function () {
  8258. if (document.exitFullscreen) {
  8259. document.exitFullscreen();
  8260. }
  8261. else if (document.mozCancelFullScreen) {
  8262. document.mozCancelFullScreen();
  8263. }
  8264. else if (document.webkitCancelFullScreen) {
  8265. document.webkitCancelFullScreen();
  8266. }
  8267. else if (document.msCancelFullScreen) {
  8268. document.msCancelFullScreen();
  8269. }
  8270. };
  8271. Tools.SetCorsBehavior = function (url, element) {
  8272. if (url && url.indexOf("data:") === 0) {
  8273. return;
  8274. }
  8275. if (Tools.CorsBehavior) {
  8276. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8277. element.crossOrigin = Tools.CorsBehavior;
  8278. }
  8279. else {
  8280. var result = Tools.CorsBehavior(url);
  8281. if (result) {
  8282. element.crossOrigin = result;
  8283. }
  8284. }
  8285. }
  8286. };
  8287. // External files
  8288. Tools.CleanUrl = function (url) {
  8289. url = url.replace(/#/mg, "%23");
  8290. return url;
  8291. };
  8292. Tools.LoadImage = function (url, onLoad, onError, database) {
  8293. if (url instanceof ArrayBuffer) {
  8294. url = Tools.EncodeArrayBufferTobase64(url);
  8295. }
  8296. url = Tools.CleanUrl(url);
  8297. url = Tools.PreprocessUrl(url);
  8298. var img = new Image();
  8299. Tools.SetCorsBehavior(url, img);
  8300. var loadHandler = function () {
  8301. img.removeEventListener("load", loadHandler);
  8302. img.removeEventListener("error", errorHandler);
  8303. onLoad(img);
  8304. };
  8305. var errorHandler = function (err) {
  8306. img.removeEventListener("load", loadHandler);
  8307. img.removeEventListener("error", errorHandler);
  8308. Tools.Error("Error while trying to load image: " + url);
  8309. if (onError) {
  8310. onError("Error while trying to load image: " + url, err);
  8311. }
  8312. };
  8313. img.addEventListener("load", loadHandler);
  8314. img.addEventListener("error", errorHandler);
  8315. var noIndexedDB = function () {
  8316. img.src = url;
  8317. };
  8318. var loadFromIndexedDB = function () {
  8319. if (database) {
  8320. database.loadImageFromDB(url, img);
  8321. }
  8322. };
  8323. //ANY database to do!
  8324. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8325. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8326. }
  8327. else {
  8328. if (url.indexOf("file:") !== -1) {
  8329. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8330. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8331. try {
  8332. var blobURL;
  8333. try {
  8334. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8335. }
  8336. catch (ex) {
  8337. // Chrome doesn't support oneTimeOnly parameter
  8338. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8339. }
  8340. img.src = blobURL;
  8341. }
  8342. catch (e) {
  8343. img.src = "";
  8344. }
  8345. return img;
  8346. }
  8347. }
  8348. noIndexedDB();
  8349. }
  8350. return img;
  8351. };
  8352. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8353. url = Tools.CleanUrl(url);
  8354. url = Tools.PreprocessUrl(url);
  8355. // If file and file input are set
  8356. if (url.indexOf("file:") !== -1) {
  8357. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8358. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8359. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8360. }
  8361. }
  8362. var loadUrl = Tools.BaseUrl + url;
  8363. var aborted = false;
  8364. var fileRequest = {
  8365. onCompleteObservable: new BABYLON.Observable(),
  8366. abort: function () { return aborted = true; },
  8367. };
  8368. var requestFile = function () {
  8369. var request = new XMLHttpRequest();
  8370. var retryHandle = null;
  8371. fileRequest.abort = function () {
  8372. aborted = true;
  8373. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8374. request.abort();
  8375. }
  8376. if (retryHandle !== null) {
  8377. clearTimeout(retryHandle);
  8378. retryHandle = null;
  8379. }
  8380. };
  8381. var retryLoop = function (retryIndex) {
  8382. request.open('GET', loadUrl, true);
  8383. if (useArrayBuffer) {
  8384. request.responseType = "arraybuffer";
  8385. }
  8386. if (onProgress) {
  8387. request.addEventListener("progress", onProgress);
  8388. }
  8389. var onLoadEnd = function () {
  8390. request.removeEventListener("loadend", onLoadEnd);
  8391. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8392. fileRequest.onCompleteObservable.clear();
  8393. };
  8394. request.addEventListener("loadend", onLoadEnd);
  8395. var onReadyStateChange = function () {
  8396. if (aborted) {
  8397. return;
  8398. }
  8399. // In case of undefined state in some browsers.
  8400. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8401. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8402. request.removeEventListener("readystatechange", onReadyStateChange);
  8403. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8404. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8405. return;
  8406. }
  8407. var retryStrategy = Tools.DefaultRetryStrategy;
  8408. if (retryStrategy) {
  8409. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8410. if (waitTime !== -1) {
  8411. // Prevent the request from completing for retry.
  8412. request.removeEventListener("loadend", onLoadEnd);
  8413. request = new XMLHttpRequest();
  8414. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8415. return;
  8416. }
  8417. }
  8418. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8419. if (onError) {
  8420. onError(request, e);
  8421. }
  8422. else {
  8423. throw e;
  8424. }
  8425. }
  8426. };
  8427. request.addEventListener("readystatechange", onReadyStateChange);
  8428. request.send();
  8429. };
  8430. retryLoop(0);
  8431. };
  8432. // Caching all files
  8433. if (database && database.enableSceneOffline) {
  8434. var noIndexedDB_1 = function () {
  8435. if (!aborted) {
  8436. requestFile();
  8437. }
  8438. };
  8439. var loadFromIndexedDB = function () {
  8440. // TODO: database needs to support aborting and should return a IFileRequest
  8441. if (aborted) {
  8442. return;
  8443. }
  8444. if (database) {
  8445. database.loadFileFromDB(url, function (data) {
  8446. if (!aborted) {
  8447. onSuccess(data);
  8448. }
  8449. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8450. }, onProgress ? function (event) {
  8451. if (!aborted) {
  8452. onProgress(event);
  8453. }
  8454. } : undefined, noIndexedDB_1, useArrayBuffer);
  8455. }
  8456. };
  8457. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8458. }
  8459. else {
  8460. requestFile();
  8461. }
  8462. return fileRequest;
  8463. };
  8464. /**
  8465. * Load a script (identified by an url). When the url returns, the
  8466. * content of this file is added into a new script element, attached to the DOM (body element)
  8467. */
  8468. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8469. var head = document.getElementsByTagName('head')[0];
  8470. var script = document.createElement('script');
  8471. script.type = 'text/javascript';
  8472. script.src = scriptUrl;
  8473. script.onload = function () {
  8474. if (onSuccess) {
  8475. onSuccess();
  8476. }
  8477. };
  8478. script.onerror = function (e) {
  8479. if (onError) {
  8480. onError("Unable to load script", e);
  8481. }
  8482. };
  8483. head.appendChild(script);
  8484. };
  8485. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8486. var reader = new FileReader();
  8487. var request = {
  8488. onCompleteObservable: new BABYLON.Observable(),
  8489. abort: function () { return reader.abort(); },
  8490. };
  8491. reader.onloadend = function (e) {
  8492. request.onCompleteObservable.notifyObservers(request);
  8493. };
  8494. reader.onload = function (e) {
  8495. //target doesn't have result from ts 1.3
  8496. callback(e.target['result']);
  8497. };
  8498. reader.onprogress = progressCallback;
  8499. reader.readAsDataURL(fileToLoad);
  8500. return request;
  8501. };
  8502. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8503. var reader = new FileReader();
  8504. var request = {
  8505. onCompleteObservable: new BABYLON.Observable(),
  8506. abort: function () { return reader.abort(); },
  8507. };
  8508. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8509. reader.onerror = function (e) {
  8510. Tools.Log("Error while reading file: " + fileToLoad.name);
  8511. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8512. };
  8513. reader.onload = function (e) {
  8514. //target doesn't have result from ts 1.3
  8515. callback(e.target['result']);
  8516. };
  8517. if (progressCallBack) {
  8518. reader.onprogress = progressCallBack;
  8519. }
  8520. if (!useArrayBuffer) {
  8521. // Asynchronous read
  8522. reader.readAsText(fileToLoad);
  8523. }
  8524. else {
  8525. reader.readAsArrayBuffer(fileToLoad);
  8526. }
  8527. return request;
  8528. };
  8529. //returns a downloadable url to a file content.
  8530. Tools.FileAsURL = function (content) {
  8531. var fileBlob = new Blob([content]);
  8532. var url = window.URL || window.webkitURL;
  8533. var link = url.createObjectURL(fileBlob);
  8534. return link;
  8535. };
  8536. // Misc.
  8537. Tools.Format = function (value, decimals) {
  8538. if (decimals === void 0) { decimals = 2; }
  8539. return value.toFixed(decimals);
  8540. };
  8541. Tools.CheckExtends = function (v, min, max) {
  8542. if (v.x < min.x)
  8543. min.x = v.x;
  8544. if (v.y < min.y)
  8545. min.y = v.y;
  8546. if (v.z < min.z)
  8547. min.z = v.z;
  8548. if (v.x > max.x)
  8549. max.x = v.x;
  8550. if (v.y > max.y)
  8551. max.y = v.y;
  8552. if (v.z > max.z)
  8553. max.z = v.z;
  8554. };
  8555. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8556. for (var prop in source) {
  8557. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8558. continue;
  8559. }
  8560. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8561. continue;
  8562. }
  8563. var sourceValue = source[prop];
  8564. var typeOfSourceValue = typeof sourceValue;
  8565. if (typeOfSourceValue === "function") {
  8566. continue;
  8567. }
  8568. try {
  8569. if (typeOfSourceValue === "object") {
  8570. if (sourceValue instanceof Array) {
  8571. destination[prop] = [];
  8572. if (sourceValue.length > 0) {
  8573. if (typeof sourceValue[0] == "object") {
  8574. for (var index = 0; index < sourceValue.length; index++) {
  8575. var clonedValue = cloneValue(sourceValue[index], destination);
  8576. if (destination[prop].indexOf(clonedValue) === -1) {
  8577. destination[prop].push(clonedValue);
  8578. }
  8579. }
  8580. }
  8581. else {
  8582. destination[prop] = sourceValue.slice(0);
  8583. }
  8584. }
  8585. }
  8586. else {
  8587. destination[prop] = cloneValue(sourceValue, destination);
  8588. }
  8589. }
  8590. else {
  8591. destination[prop] = sourceValue;
  8592. }
  8593. }
  8594. catch (e) {
  8595. // Just ignore error (it could be because of a read-only property)
  8596. }
  8597. }
  8598. };
  8599. Tools.IsEmpty = function (obj) {
  8600. for (var i in obj) {
  8601. if (obj.hasOwnProperty(i)) {
  8602. return false;
  8603. }
  8604. }
  8605. return true;
  8606. };
  8607. Tools.RegisterTopRootEvents = function (events) {
  8608. for (var index = 0; index < events.length; index++) {
  8609. var event = events[index];
  8610. window.addEventListener(event.name, event.handler, false);
  8611. try {
  8612. if (window.parent) {
  8613. window.parent.addEventListener(event.name, event.handler, false);
  8614. }
  8615. }
  8616. catch (e) {
  8617. // Silently fails...
  8618. }
  8619. }
  8620. };
  8621. Tools.UnregisterTopRootEvents = function (events) {
  8622. for (var index = 0; index < events.length; index++) {
  8623. var event = events[index];
  8624. window.removeEventListener(event.name, event.handler);
  8625. try {
  8626. if (window.parent) {
  8627. window.parent.removeEventListener(event.name, event.handler);
  8628. }
  8629. }
  8630. catch (e) {
  8631. // Silently fails...
  8632. }
  8633. }
  8634. };
  8635. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8636. if (mimeType === void 0) { mimeType = "image/png"; }
  8637. // Read the contents of the framebuffer
  8638. var numberOfChannelsByLine = width * 4;
  8639. var halfHeight = height / 2;
  8640. //Reading datas from WebGL
  8641. var data = engine.readPixels(0, 0, width, height);
  8642. //To flip image on Y axis.
  8643. for (var i = 0; i < halfHeight; i++) {
  8644. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8645. var currentCell = j + i * numberOfChannelsByLine;
  8646. var targetLine = height - i - 1;
  8647. var targetCell = j + targetLine * numberOfChannelsByLine;
  8648. var temp = data[currentCell];
  8649. data[currentCell] = data[targetCell];
  8650. data[targetCell] = temp;
  8651. }
  8652. }
  8653. // Create a 2D canvas to store the result
  8654. if (!screenshotCanvas) {
  8655. screenshotCanvas = document.createElement('canvas');
  8656. }
  8657. screenshotCanvas.width = width;
  8658. screenshotCanvas.height = height;
  8659. var context = screenshotCanvas.getContext('2d');
  8660. if (context) {
  8661. // Copy the pixels to a 2D canvas
  8662. var imageData = context.createImageData(width, height);
  8663. var castData = (imageData.data);
  8664. castData.set(data);
  8665. context.putImageData(imageData, 0, 0);
  8666. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8667. }
  8668. };
  8669. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8670. if (mimeType === void 0) { mimeType = "image/png"; }
  8671. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8672. if (successCallback) {
  8673. successCallback(base64Image);
  8674. }
  8675. else {
  8676. // We need HTMLCanvasElement.toBlob for HD screenshots
  8677. if (!screenshotCanvas.toBlob) {
  8678. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8679. screenshotCanvas.toBlob = function (callback, type, quality) {
  8680. var _this = this;
  8681. setTimeout(function () {
  8682. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8683. for (var i = 0; i < len; i++) {
  8684. arr[i] = binStr.charCodeAt(i);
  8685. }
  8686. callback(new Blob([arr], { type: type || 'image/png' }));
  8687. });
  8688. };
  8689. }
  8690. screenshotCanvas.toBlob(function (blob) {
  8691. var url = URL.createObjectURL(blob);
  8692. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8693. if (("download" in document.createElement("a"))) {
  8694. var a = window.document.createElement("a");
  8695. a.href = url;
  8696. if (fileName) {
  8697. a.setAttribute("download", fileName);
  8698. }
  8699. else {
  8700. var date = new Date();
  8701. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8702. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8703. }
  8704. window.document.body.appendChild(a);
  8705. a.addEventListener("click", function () {
  8706. if (a.parentElement) {
  8707. a.parentElement.removeChild(a);
  8708. }
  8709. });
  8710. a.click();
  8711. }
  8712. else {
  8713. var newWindow = window.open("");
  8714. if (!newWindow)
  8715. return;
  8716. var img = newWindow.document.createElement("img");
  8717. img.onload = function () {
  8718. // no longer need to read the blob so it's revoked
  8719. URL.revokeObjectURL(url);
  8720. };
  8721. img.src = url;
  8722. newWindow.document.body.appendChild(img);
  8723. }
  8724. });
  8725. }
  8726. };
  8727. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8728. if (mimeType === void 0) { mimeType = "image/png"; }
  8729. var width;
  8730. var height;
  8731. // If a precision value is specified
  8732. if (size.precision) {
  8733. width = Math.round(engine.getRenderWidth() * size.precision);
  8734. height = Math.round(width / engine.getAspectRatio(camera));
  8735. }
  8736. else if (size.width && size.height) {
  8737. width = size.width;
  8738. height = size.height;
  8739. }
  8740. else if (size.width && !size.height) {
  8741. width = size.width;
  8742. height = Math.round(width / engine.getAspectRatio(camera));
  8743. }
  8744. else if (size.height && !size.width) {
  8745. height = size.height;
  8746. width = Math.round(height * engine.getAspectRatio(camera));
  8747. }
  8748. else if (!isNaN(size)) {
  8749. height = size;
  8750. width = size;
  8751. }
  8752. else {
  8753. Tools.Error("Invalid 'size' parameter !");
  8754. return;
  8755. }
  8756. if (!screenshotCanvas) {
  8757. screenshotCanvas = document.createElement('canvas');
  8758. }
  8759. screenshotCanvas.width = width;
  8760. screenshotCanvas.height = height;
  8761. var renderContext = screenshotCanvas.getContext("2d");
  8762. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8763. var newWidth = width;
  8764. var newHeight = newWidth / ratio;
  8765. if (newHeight > height) {
  8766. newHeight = height;
  8767. newWidth = newHeight * ratio;
  8768. }
  8769. var offsetX = Math.max(0, width - newWidth) / 2;
  8770. var offsetY = Math.max(0, height - newHeight) / 2;
  8771. var renderingCanvas = engine.getRenderingCanvas();
  8772. if (renderContext && renderingCanvas) {
  8773. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8774. }
  8775. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8776. };
  8777. /**
  8778. * Generates an image screenshot from the specified camera.
  8779. *
  8780. * @param engine The engine to use for rendering
  8781. * @param camera The camera to use for rendering
  8782. * @param size This parameter can be set to a single number or to an object with the
  8783. * following (optional) properties: precision, width, height. If a single number is passed,
  8784. * it will be used for both width and height. If an object is passed, the screenshot size
  8785. * will be derived from the parameters. The precision property is a multiplier allowing
  8786. * rendering at a higher or lower resolution.
  8787. * @param successCallback The callback receives a single parameter which contains the
  8788. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8789. * src parameter of an <img> to display it.
  8790. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8791. * Check your browser for supported MIME types.
  8792. * @param samples Texture samples (default: 1)
  8793. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8794. * @param fileName A name for for the downloaded file.
  8795. * @constructor
  8796. */
  8797. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8798. if (mimeType === void 0) { mimeType = "image/png"; }
  8799. if (samples === void 0) { samples = 1; }
  8800. if (antialiasing === void 0) { antialiasing = false; }
  8801. var width;
  8802. var height;
  8803. //If a precision value is specified
  8804. if (size.precision) {
  8805. width = Math.round(engine.getRenderWidth() * size.precision);
  8806. height = Math.round(width / engine.getAspectRatio(camera));
  8807. size = { width: width, height: height };
  8808. }
  8809. else if (size.width && size.height) {
  8810. width = size.width;
  8811. height = size.height;
  8812. }
  8813. else if (size.width && !size.height) {
  8814. width = size.width;
  8815. height = Math.round(width / engine.getAspectRatio(camera));
  8816. size = { width: width, height: height };
  8817. }
  8818. else if (size.height && !size.width) {
  8819. height = size.height;
  8820. width = Math.round(height * engine.getAspectRatio(camera));
  8821. size = { width: width, height: height };
  8822. }
  8823. else if (!isNaN(size)) {
  8824. height = size;
  8825. width = size;
  8826. }
  8827. else {
  8828. Tools.Error("Invalid 'size' parameter !");
  8829. return;
  8830. }
  8831. var scene = camera.getScene();
  8832. var previousCamera = null;
  8833. if (scene.activeCamera !== camera) {
  8834. previousCamera = scene.activeCamera;
  8835. scene.activeCamera = camera;
  8836. }
  8837. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8838. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8839. texture.renderList = null;
  8840. texture.samples = samples;
  8841. if (antialiasing) {
  8842. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8843. }
  8844. texture.onAfterRenderObservable.add(function () {
  8845. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8846. });
  8847. scene.incrementRenderId();
  8848. scene.resetCachedMaterial();
  8849. texture.render(true);
  8850. texture.dispose();
  8851. if (previousCamera) {
  8852. scene.activeCamera = previousCamera;
  8853. }
  8854. camera.getProjectionMatrix(true); // Force cache refresh;
  8855. };
  8856. // XHR response validator for local file scenario
  8857. Tools.ValidateXHRData = function (xhr, dataType) {
  8858. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8859. if (dataType === void 0) { dataType = 7; }
  8860. try {
  8861. if (dataType & 1) {
  8862. if (xhr.responseText && xhr.responseText.length > 0) {
  8863. return true;
  8864. }
  8865. else if (dataType === 1) {
  8866. return false;
  8867. }
  8868. }
  8869. if (dataType & 2) {
  8870. // Check header width and height since there is no "TGA" magic number
  8871. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8872. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8873. return true;
  8874. }
  8875. else if (dataType === 2) {
  8876. return false;
  8877. }
  8878. }
  8879. if (dataType & 4) {
  8880. // Check for the "DDS" magic number
  8881. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8882. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8883. return true;
  8884. }
  8885. else {
  8886. return false;
  8887. }
  8888. }
  8889. }
  8890. catch (e) {
  8891. // Global protection
  8892. }
  8893. return false;
  8894. };
  8895. /**
  8896. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8897. * Be aware Math.random() could cause collisions, but:
  8898. * "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"
  8899. */
  8900. Tools.RandomId = function () {
  8901. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8902. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8903. return v.toString(16);
  8904. });
  8905. };
  8906. /**
  8907. * Test if the given uri is a base64 string.
  8908. * @param uri The uri to test
  8909. * @return True if the uri is a base64 string or false otherwise.
  8910. */
  8911. Tools.IsBase64 = function (uri) {
  8912. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8913. };
  8914. /**
  8915. * Decode the given base64 uri.
  8916. * @param uri The uri to decode
  8917. * @return The decoded base64 data.
  8918. */
  8919. Tools.DecodeBase64 = function (uri) {
  8920. var decodedString = atob(uri.split(",")[1]);
  8921. var bufferLength = decodedString.length;
  8922. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8923. for (var i = 0; i < bufferLength; i++) {
  8924. bufferView[i] = decodedString.charCodeAt(i);
  8925. }
  8926. return bufferView.buffer;
  8927. };
  8928. Object.defineProperty(Tools, "NoneLogLevel", {
  8929. get: function () {
  8930. return Tools._NoneLogLevel;
  8931. },
  8932. enumerable: true,
  8933. configurable: true
  8934. });
  8935. Object.defineProperty(Tools, "MessageLogLevel", {
  8936. get: function () {
  8937. return Tools._MessageLogLevel;
  8938. },
  8939. enumerable: true,
  8940. configurable: true
  8941. });
  8942. Object.defineProperty(Tools, "WarningLogLevel", {
  8943. get: function () {
  8944. return Tools._WarningLogLevel;
  8945. },
  8946. enumerable: true,
  8947. configurable: true
  8948. });
  8949. Object.defineProperty(Tools, "ErrorLogLevel", {
  8950. get: function () {
  8951. return Tools._ErrorLogLevel;
  8952. },
  8953. enumerable: true,
  8954. configurable: true
  8955. });
  8956. Object.defineProperty(Tools, "AllLogLevel", {
  8957. get: function () {
  8958. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8959. },
  8960. enumerable: true,
  8961. configurable: true
  8962. });
  8963. Tools._AddLogEntry = function (entry) {
  8964. Tools._LogCache = entry + Tools._LogCache;
  8965. if (Tools.OnNewCacheEntry) {
  8966. Tools.OnNewCacheEntry(entry);
  8967. }
  8968. };
  8969. Tools._FormatMessage = function (message) {
  8970. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8971. var date = new Date();
  8972. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8973. };
  8974. Tools._LogDisabled = function (message) {
  8975. // nothing to do
  8976. };
  8977. Tools._LogEnabled = function (message) {
  8978. var formattedMessage = Tools._FormatMessage(message);
  8979. console.log("BJS - " + formattedMessage);
  8980. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8981. Tools._AddLogEntry(entry);
  8982. };
  8983. Tools._WarnDisabled = function (message) {
  8984. // nothing to do
  8985. };
  8986. Tools._WarnEnabled = function (message) {
  8987. var formattedMessage = Tools._FormatMessage(message);
  8988. console.warn("BJS - " + formattedMessage);
  8989. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8990. Tools._AddLogEntry(entry);
  8991. };
  8992. Tools._ErrorDisabled = function (message) {
  8993. // nothing to do
  8994. };
  8995. Tools._ErrorEnabled = function (message) {
  8996. Tools.errorsCount++;
  8997. var formattedMessage = Tools._FormatMessage(message);
  8998. console.error("BJS - " + formattedMessage);
  8999. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9000. Tools._AddLogEntry(entry);
  9001. };
  9002. Object.defineProperty(Tools, "LogCache", {
  9003. get: function () {
  9004. return Tools._LogCache;
  9005. },
  9006. enumerable: true,
  9007. configurable: true
  9008. });
  9009. Tools.ClearLogCache = function () {
  9010. Tools._LogCache = "";
  9011. Tools.errorsCount = 0;
  9012. };
  9013. Object.defineProperty(Tools, "LogLevels", {
  9014. set: function (level) {
  9015. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9016. Tools.Log = Tools._LogEnabled;
  9017. }
  9018. else {
  9019. Tools.Log = Tools._LogDisabled;
  9020. }
  9021. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9022. Tools.Warn = Tools._WarnEnabled;
  9023. }
  9024. else {
  9025. Tools.Warn = Tools._WarnDisabled;
  9026. }
  9027. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9028. Tools.Error = Tools._ErrorEnabled;
  9029. }
  9030. else {
  9031. Tools.Error = Tools._ErrorDisabled;
  9032. }
  9033. },
  9034. enumerable: true,
  9035. configurable: true
  9036. });
  9037. Tools.IsWindowObjectExist = function () {
  9038. return (typeof window) !== "undefined";
  9039. };
  9040. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9041. get: function () {
  9042. return Tools._PerformanceNoneLogLevel;
  9043. },
  9044. enumerable: true,
  9045. configurable: true
  9046. });
  9047. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9048. get: function () {
  9049. return Tools._PerformanceUserMarkLogLevel;
  9050. },
  9051. enumerable: true,
  9052. configurable: true
  9053. });
  9054. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9055. get: function () {
  9056. return Tools._PerformanceConsoleLogLevel;
  9057. },
  9058. enumerable: true,
  9059. configurable: true
  9060. });
  9061. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9062. set: function (level) {
  9063. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9064. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9065. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9066. return;
  9067. }
  9068. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9069. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9070. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9071. return;
  9072. }
  9073. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9074. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9075. },
  9076. enumerable: true,
  9077. configurable: true
  9078. });
  9079. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9080. };
  9081. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9082. };
  9083. Tools._StartUserMark = function (counterName, condition) {
  9084. if (condition === void 0) { condition = true; }
  9085. if (!Tools._performance) {
  9086. if (!Tools.IsWindowObjectExist()) {
  9087. return;
  9088. }
  9089. Tools._performance = window.performance;
  9090. }
  9091. if (!condition || !Tools._performance.mark) {
  9092. return;
  9093. }
  9094. Tools._performance.mark(counterName + "-Begin");
  9095. };
  9096. Tools._EndUserMark = function (counterName, condition) {
  9097. if (condition === void 0) { condition = true; }
  9098. if (!condition || !Tools._performance.mark) {
  9099. return;
  9100. }
  9101. Tools._performance.mark(counterName + "-End");
  9102. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9103. };
  9104. Tools._StartPerformanceConsole = function (counterName, condition) {
  9105. if (condition === void 0) { condition = true; }
  9106. if (!condition) {
  9107. return;
  9108. }
  9109. Tools._StartUserMark(counterName, condition);
  9110. if (console.time) {
  9111. console.time(counterName);
  9112. }
  9113. };
  9114. Tools._EndPerformanceConsole = function (counterName, condition) {
  9115. if (condition === void 0) { condition = true; }
  9116. if (!condition) {
  9117. return;
  9118. }
  9119. Tools._EndUserMark(counterName, condition);
  9120. if (console.time) {
  9121. console.timeEnd(counterName);
  9122. }
  9123. };
  9124. Object.defineProperty(Tools, "Now", {
  9125. get: function () {
  9126. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9127. return window.performance.now();
  9128. }
  9129. return new Date().getTime();
  9130. },
  9131. enumerable: true,
  9132. configurable: true
  9133. });
  9134. /**
  9135. * This method will return the name of the class used to create the instance of the given object.
  9136. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9137. * @param object the object to get the class name from
  9138. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9139. */
  9140. Tools.GetClassName = function (object, isType) {
  9141. if (isType === void 0) { isType = false; }
  9142. var name = null;
  9143. if (!isType && object.getClassName) {
  9144. name = object.getClassName();
  9145. }
  9146. else {
  9147. if (object instanceof Object) {
  9148. var classObj = isType ? object : Object.getPrototypeOf(object);
  9149. name = classObj.constructor["__bjsclassName__"];
  9150. }
  9151. if (!name) {
  9152. name = typeof object;
  9153. }
  9154. }
  9155. return name;
  9156. };
  9157. Tools.First = function (array, predicate) {
  9158. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9159. var el = array_1[_i];
  9160. if (predicate(el)) {
  9161. return el;
  9162. }
  9163. }
  9164. return null;
  9165. };
  9166. /**
  9167. * This method will return the name of the full name of the class, including its owning module (if any).
  9168. * 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).
  9169. * @param object the object to get the class name from
  9170. * @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.
  9171. */
  9172. Tools.getFullClassName = function (object, isType) {
  9173. if (isType === void 0) { isType = false; }
  9174. var className = null;
  9175. var moduleName = null;
  9176. if (!isType && object.getClassName) {
  9177. className = object.getClassName();
  9178. }
  9179. else {
  9180. if (object instanceof Object) {
  9181. var classObj = isType ? object : Object.getPrototypeOf(object);
  9182. className = classObj.constructor["__bjsclassName__"];
  9183. moduleName = classObj.constructor["__bjsmoduleName__"];
  9184. }
  9185. if (!className) {
  9186. className = typeof object;
  9187. }
  9188. }
  9189. if (!className) {
  9190. return null;
  9191. }
  9192. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9193. };
  9194. /**
  9195. * 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.
  9196. * @param array
  9197. */
  9198. Tools.arrayOrStringFeeder = function (array) {
  9199. return function (index) {
  9200. if (index >= array.length) {
  9201. return null;
  9202. }
  9203. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9204. if (val && val.getHashCode) {
  9205. val = val.getHashCode();
  9206. }
  9207. if (typeof val === "string") {
  9208. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9209. }
  9210. return val;
  9211. };
  9212. };
  9213. /**
  9214. * Compute the hashCode of a stream of number
  9215. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9216. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9217. * @return the hash code computed
  9218. */
  9219. Tools.hashCodeFromStream = function (feeder) {
  9220. // Based from here: http://stackoverflow.com/a/7616484/802124
  9221. var hash = 0;
  9222. var index = 0;
  9223. var chr = feeder(index++);
  9224. while (chr != null) {
  9225. hash = ((hash << 5) - hash) + chr;
  9226. hash |= 0; // Convert to 32bit integer
  9227. chr = feeder(index++);
  9228. }
  9229. return hash;
  9230. };
  9231. /**
  9232. * Returns a promise that resolves after the given amount of time.
  9233. * @param delay Number of milliseconds to delay
  9234. * @returns Promise that resolves after the given amount of time
  9235. */
  9236. Tools.DelayAsync = function (delay) {
  9237. return new Promise(function (resolve) {
  9238. setTimeout(function () {
  9239. resolve();
  9240. }, delay);
  9241. });
  9242. };
  9243. Tools.BaseUrl = "";
  9244. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9245. /**
  9246. * Default behaviour for cors in the application.
  9247. * It can be a string if the expected behavior is identical in the entire app.
  9248. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9249. */
  9250. Tools.CorsBehavior = "anonymous";
  9251. Tools.UseFallbackTexture = true;
  9252. /**
  9253. * Use this object to register external classes like custom textures or material
  9254. * to allow the laoders to instantiate them
  9255. */
  9256. Tools.RegisteredExternalClasses = {};
  9257. // Used in case of a texture loading problem
  9258. 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";
  9259. Tools.PreprocessUrl = function (url) {
  9260. return url;
  9261. };
  9262. // Logs
  9263. Tools._NoneLogLevel = 0;
  9264. Tools._MessageLogLevel = 1;
  9265. Tools._WarningLogLevel = 2;
  9266. Tools._ErrorLogLevel = 4;
  9267. Tools._LogCache = "";
  9268. Tools.errorsCount = 0;
  9269. Tools.Log = Tools._LogEnabled;
  9270. Tools.Warn = Tools._WarnEnabled;
  9271. Tools.Error = Tools._ErrorEnabled;
  9272. // Performances
  9273. Tools._PerformanceNoneLogLevel = 0;
  9274. Tools._PerformanceUserMarkLogLevel = 1;
  9275. Tools._PerformanceConsoleLogLevel = 2;
  9276. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9277. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9278. return Tools;
  9279. }());
  9280. BABYLON.Tools = Tools;
  9281. /**
  9282. * This class is used to track a performance counter which is number based.
  9283. * The user has access to many properties which give statistics of different nature
  9284. *
  9285. * The implementer can track two kinds of Performance Counter: time and count
  9286. * 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.
  9287. * 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.
  9288. */
  9289. var PerfCounter = /** @class */ (function () {
  9290. function PerfCounter() {
  9291. this._startMonitoringTime = 0;
  9292. this._min = 0;
  9293. this._max = 0;
  9294. this._average = 0;
  9295. this._lastSecAverage = 0;
  9296. this._current = 0;
  9297. this._totalValueCount = 0;
  9298. this._totalAccumulated = 0;
  9299. this._lastSecAccumulated = 0;
  9300. this._lastSecTime = 0;
  9301. this._lastSecValueCount = 0;
  9302. }
  9303. Object.defineProperty(PerfCounter.prototype, "min", {
  9304. /**
  9305. * Returns the smallest value ever
  9306. */
  9307. get: function () {
  9308. return this._min;
  9309. },
  9310. enumerable: true,
  9311. configurable: true
  9312. });
  9313. Object.defineProperty(PerfCounter.prototype, "max", {
  9314. /**
  9315. * Returns the biggest value ever
  9316. */
  9317. get: function () {
  9318. return this._max;
  9319. },
  9320. enumerable: true,
  9321. configurable: true
  9322. });
  9323. Object.defineProperty(PerfCounter.prototype, "average", {
  9324. /**
  9325. * Returns the average value since the performance counter is running
  9326. */
  9327. get: function () {
  9328. return this._average;
  9329. },
  9330. enumerable: true,
  9331. configurable: true
  9332. });
  9333. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9334. /**
  9335. * Returns the average value of the last second the counter was monitored
  9336. */
  9337. get: function () {
  9338. return this._lastSecAverage;
  9339. },
  9340. enumerable: true,
  9341. configurable: true
  9342. });
  9343. Object.defineProperty(PerfCounter.prototype, "current", {
  9344. /**
  9345. * Returns the current value
  9346. */
  9347. get: function () {
  9348. return this._current;
  9349. },
  9350. enumerable: true,
  9351. configurable: true
  9352. });
  9353. Object.defineProperty(PerfCounter.prototype, "total", {
  9354. get: function () {
  9355. return this._totalAccumulated;
  9356. },
  9357. enumerable: true,
  9358. configurable: true
  9359. });
  9360. Object.defineProperty(PerfCounter.prototype, "count", {
  9361. get: function () {
  9362. return this._totalValueCount;
  9363. },
  9364. enumerable: true,
  9365. configurable: true
  9366. });
  9367. /**
  9368. * Call this method to start monitoring a new frame.
  9369. * 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.
  9370. */
  9371. PerfCounter.prototype.fetchNewFrame = function () {
  9372. this._totalValueCount++;
  9373. this._current = 0;
  9374. this._lastSecValueCount++;
  9375. };
  9376. /**
  9377. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9378. * @param newCount the count value to add to the monitored count
  9379. * @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.
  9380. */
  9381. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9382. if (!PerfCounter.Enabled) {
  9383. return;
  9384. }
  9385. this._current += newCount;
  9386. if (fetchResult) {
  9387. this._fetchResult();
  9388. }
  9389. };
  9390. /**
  9391. * Start monitoring this performance counter
  9392. */
  9393. PerfCounter.prototype.beginMonitoring = function () {
  9394. if (!PerfCounter.Enabled) {
  9395. return;
  9396. }
  9397. this._startMonitoringTime = Tools.Now;
  9398. };
  9399. /**
  9400. * Compute the time lapsed since the previous beginMonitoring() call.
  9401. * @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
  9402. */
  9403. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9404. if (newFrame === void 0) { newFrame = true; }
  9405. if (!PerfCounter.Enabled) {
  9406. return;
  9407. }
  9408. if (newFrame) {
  9409. this.fetchNewFrame();
  9410. }
  9411. var currentTime = Tools.Now;
  9412. this._current = currentTime - this._startMonitoringTime;
  9413. if (newFrame) {
  9414. this._fetchResult();
  9415. }
  9416. };
  9417. PerfCounter.prototype._fetchResult = function () {
  9418. this._totalAccumulated += this._current;
  9419. this._lastSecAccumulated += this._current;
  9420. // Min/Max update
  9421. this._min = Math.min(this._min, this._current);
  9422. this._max = Math.max(this._max, this._current);
  9423. this._average = this._totalAccumulated / this._totalValueCount;
  9424. // Reset last sec?
  9425. var now = Tools.Now;
  9426. if ((now - this._lastSecTime) > 1000) {
  9427. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9428. this._lastSecTime = now;
  9429. this._lastSecAccumulated = 0;
  9430. this._lastSecValueCount = 0;
  9431. }
  9432. };
  9433. PerfCounter.Enabled = true;
  9434. return PerfCounter;
  9435. }());
  9436. BABYLON.PerfCounter = PerfCounter;
  9437. /**
  9438. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9439. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9440. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9441. * @param name The name of the class, case should be preserved
  9442. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9443. */
  9444. function className(name, module) {
  9445. return function (target) {
  9446. target["__bjsclassName__"] = name;
  9447. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9448. };
  9449. }
  9450. BABYLON.className = className;
  9451. /**
  9452. * An implementation of a loop for asynchronous functions.
  9453. */
  9454. var AsyncLoop = /** @class */ (function () {
  9455. /**
  9456. * Constroctor.
  9457. * @param iterations the number of iterations.
  9458. * @param _fn the function to run each iteration
  9459. * @param _successCallback the callback that will be called upon succesful execution
  9460. * @param offset starting offset.
  9461. */
  9462. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9463. if (offset === void 0) { offset = 0; }
  9464. this.iterations = iterations;
  9465. this._fn = _fn;
  9466. this._successCallback = _successCallback;
  9467. this.index = offset - 1;
  9468. this._done = false;
  9469. }
  9470. /**
  9471. * Execute the next iteration. Must be called after the last iteration was finished.
  9472. */
  9473. AsyncLoop.prototype.executeNext = function () {
  9474. if (!this._done) {
  9475. if (this.index + 1 < this.iterations) {
  9476. ++this.index;
  9477. this._fn(this);
  9478. }
  9479. else {
  9480. this.breakLoop();
  9481. }
  9482. }
  9483. };
  9484. /**
  9485. * Break the loop and run the success callback.
  9486. */
  9487. AsyncLoop.prototype.breakLoop = function () {
  9488. this._done = true;
  9489. this._successCallback();
  9490. };
  9491. /**
  9492. * Helper function
  9493. */
  9494. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9495. if (offset === void 0) { offset = 0; }
  9496. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9497. loop.executeNext();
  9498. return loop;
  9499. };
  9500. /**
  9501. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9502. * @param iterations total number of iterations
  9503. * @param syncedIterations number of synchronous iterations in each async iteration.
  9504. * @param fn the function to call each iteration.
  9505. * @param callback a success call back that will be called when iterating stops.
  9506. * @param breakFunction a break condition (optional)
  9507. * @param timeout timeout settings for the setTimeout function. default - 0.
  9508. * @constructor
  9509. */
  9510. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9511. if (timeout === void 0) { timeout = 0; }
  9512. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9513. if (breakFunction && breakFunction())
  9514. loop.breakLoop();
  9515. else {
  9516. setTimeout(function () {
  9517. for (var i = 0; i < syncedIterations; ++i) {
  9518. var iteration = (loop.index * syncedIterations) + i;
  9519. if (iteration >= iterations)
  9520. break;
  9521. fn(iteration);
  9522. if (breakFunction && breakFunction()) {
  9523. loop.breakLoop();
  9524. break;
  9525. }
  9526. }
  9527. loop.executeNext();
  9528. }, timeout);
  9529. }
  9530. }, callback);
  9531. };
  9532. return AsyncLoop;
  9533. }());
  9534. BABYLON.AsyncLoop = AsyncLoop;
  9535. })(BABYLON || (BABYLON = {}));
  9536. //# sourceMappingURL=babylon.tools.js.map
  9537. "use strict";
  9538. var BABYLON;
  9539. (function (BABYLON) {
  9540. var PromiseStates;
  9541. (function (PromiseStates) {
  9542. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9543. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9544. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9545. })(PromiseStates || (PromiseStates = {}));
  9546. var FulFillmentAgregator = /** @class */ (function () {
  9547. function FulFillmentAgregator() {
  9548. this.count = 0;
  9549. this.target = 0;
  9550. this.results = [];
  9551. }
  9552. return FulFillmentAgregator;
  9553. }());
  9554. var InternalPromise = /** @class */ (function () {
  9555. function InternalPromise(resolver) {
  9556. var _this = this;
  9557. this._state = PromiseStates.Pending;
  9558. this._children = new Array();
  9559. this._rejectWasConsumed = false;
  9560. if (!resolver) {
  9561. return;
  9562. }
  9563. try {
  9564. resolver(function (value) {
  9565. _this._resolve(value);
  9566. }, function (reason) {
  9567. _this._reject(reason);
  9568. });
  9569. }
  9570. catch (e) {
  9571. this._reject(e);
  9572. }
  9573. }
  9574. InternalPromise.prototype.catch = function (onRejected) {
  9575. return this.then(undefined, onRejected);
  9576. };
  9577. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9578. var _this = this;
  9579. var newPromise = new InternalPromise();
  9580. newPromise._onFulfilled = onFulfilled;
  9581. newPromise._onRejected = onRejected;
  9582. // Composition
  9583. this._children.push(newPromise);
  9584. if (this._state !== PromiseStates.Pending) {
  9585. BABYLON.Tools.SetImmediate(function () {
  9586. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9587. var returnedValue = newPromise._resolve(_this._result);
  9588. if (returnedValue !== undefined && returnedValue !== null) {
  9589. if (returnedValue._state !== undefined) {
  9590. var returnedPromise = returnedValue;
  9591. newPromise._children.push(returnedPromise);
  9592. newPromise = returnedPromise;
  9593. }
  9594. else {
  9595. newPromise._result = returnedValue;
  9596. }
  9597. }
  9598. }
  9599. else {
  9600. newPromise._reject(_this._reason);
  9601. }
  9602. });
  9603. }
  9604. return newPromise;
  9605. };
  9606. InternalPromise.prototype._moveChildren = function (children) {
  9607. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9608. if (this._state === PromiseStates.Fulfilled) {
  9609. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9610. var child = _b[_i];
  9611. child._resolve(this._result);
  9612. }
  9613. }
  9614. else if (this._state === PromiseStates.Rejected) {
  9615. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9616. var child = _d[_c];
  9617. child._reject(this._reason);
  9618. }
  9619. }
  9620. var _a;
  9621. };
  9622. InternalPromise.prototype._resolve = function (value) {
  9623. try {
  9624. this._state = PromiseStates.Fulfilled;
  9625. this._result = value;
  9626. var returnedValue = null;
  9627. if (this._onFulfilled) {
  9628. returnedValue = this._onFulfilled(value);
  9629. }
  9630. if (returnedValue !== undefined && returnedValue !== null) {
  9631. if (returnedValue._state !== undefined) {
  9632. // Transmit children
  9633. var returnedPromise = returnedValue;
  9634. returnedPromise._moveChildren(this._children);
  9635. }
  9636. else {
  9637. value = returnedValue;
  9638. }
  9639. }
  9640. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9641. var child = _a[_i];
  9642. child._resolve(value);
  9643. }
  9644. this._children.length = 0;
  9645. delete this._onFulfilled;
  9646. delete this._onRejected;
  9647. return returnedValue;
  9648. }
  9649. catch (e) {
  9650. this._reject(e, true);
  9651. }
  9652. return null;
  9653. };
  9654. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9655. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9656. this._state = PromiseStates.Rejected;
  9657. this._reason = reason;
  9658. if (this._onRejected && !onLocalThrow) {
  9659. try {
  9660. this._onRejected(reason);
  9661. this._rejectWasConsumed = true;
  9662. }
  9663. catch (e) {
  9664. reason = e;
  9665. }
  9666. }
  9667. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9668. var child = _a[_i];
  9669. if (this._rejectWasConsumed) {
  9670. child._resolve(null);
  9671. }
  9672. else {
  9673. child._reject(reason);
  9674. }
  9675. }
  9676. this._children.length = 0;
  9677. delete this._onFulfilled;
  9678. delete this._onRejected;
  9679. };
  9680. InternalPromise.resolve = function (value) {
  9681. var newPromise = new InternalPromise();
  9682. newPromise._resolve(value);
  9683. return newPromise;
  9684. };
  9685. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9686. promise.then(function (value) {
  9687. agregator.results[index] = value;
  9688. agregator.count++;
  9689. if (agregator.count === agregator.target) {
  9690. agregator.rootPromise._resolve(agregator.results);
  9691. }
  9692. return null;
  9693. }, function (reason) {
  9694. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9695. agregator.rootPromise._reject(reason);
  9696. }
  9697. });
  9698. };
  9699. InternalPromise.all = function (promises) {
  9700. var newPromise = new InternalPromise();
  9701. var agregator = new FulFillmentAgregator();
  9702. agregator.target = promises.length;
  9703. agregator.rootPromise = newPromise;
  9704. if (promises.length) {
  9705. for (var index = 0; index < promises.length; index++) {
  9706. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9707. }
  9708. }
  9709. else {
  9710. newPromise._resolve([]);
  9711. }
  9712. return newPromise;
  9713. };
  9714. InternalPromise.race = function (promises) {
  9715. var newPromise = new InternalPromise();
  9716. if (promises.length) {
  9717. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9718. var promise = promises_1[_i];
  9719. promise.then(function (value) {
  9720. if (newPromise) {
  9721. newPromise._resolve(value);
  9722. newPromise = null;
  9723. }
  9724. return null;
  9725. }, function (reason) {
  9726. if (newPromise) {
  9727. newPromise._reject(reason);
  9728. newPromise = null;
  9729. }
  9730. });
  9731. }
  9732. }
  9733. return newPromise;
  9734. };
  9735. return InternalPromise;
  9736. }());
  9737. /**
  9738. * Helper class that provides a small promise polyfill
  9739. */
  9740. var PromisePolyfill = /** @class */ (function () {
  9741. function PromisePolyfill() {
  9742. }
  9743. /**
  9744. * Static function used to check if the polyfill is required
  9745. * If this is the case then the function will inject the polyfill to window.Promise
  9746. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9747. */
  9748. PromisePolyfill.Apply = function (force) {
  9749. if (force === void 0) { force = false; }
  9750. if (force || typeof Promise === 'undefined') {
  9751. var root = window;
  9752. root.Promise = InternalPromise;
  9753. }
  9754. };
  9755. return PromisePolyfill;
  9756. }());
  9757. BABYLON.PromisePolyfill = PromisePolyfill;
  9758. })(BABYLON || (BABYLON = {}));
  9759. //# sourceMappingURL=babylon.promise.js.map
  9760. "use strict";
  9761. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9762. var BABYLON;
  9763. (function (BABYLON) {
  9764. /**
  9765. * Helper class to push actions to a pool of workers.
  9766. */
  9767. var WorkerPool = /** @class */ (function () {
  9768. /**
  9769. * Constructor
  9770. * @param workers Array of workers to use for actions
  9771. */
  9772. function WorkerPool(workers) {
  9773. this._pendingActions = new Array();
  9774. this._workerInfos = workers.map(function (worker) { return ({
  9775. worker: worker,
  9776. active: false
  9777. }); });
  9778. }
  9779. /**
  9780. * Terminates all workers and clears any pending actions.
  9781. */
  9782. WorkerPool.prototype.dispose = function () {
  9783. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9784. var workerInfo = _a[_i];
  9785. workerInfo.worker.terminate();
  9786. }
  9787. delete this._workerInfos;
  9788. delete this._pendingActions;
  9789. };
  9790. /**
  9791. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9792. * pended until a worker has completed its action.
  9793. * @param action The action to perform. Call onComplete when the action is complete.
  9794. */
  9795. WorkerPool.prototype.push = function (action) {
  9796. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9797. var workerInfo = _a[_i];
  9798. if (!workerInfo.active) {
  9799. this._execute(workerInfo, action);
  9800. return;
  9801. }
  9802. }
  9803. this._pendingActions.push(action);
  9804. };
  9805. WorkerPool.prototype._execute = function (workerInfo, action) {
  9806. var _this = this;
  9807. workerInfo.active = true;
  9808. action(workerInfo.worker, function () {
  9809. workerInfo.active = false;
  9810. var nextAction = _this._pendingActions.shift();
  9811. if (nextAction) {
  9812. _this._execute(workerInfo, nextAction);
  9813. }
  9814. });
  9815. };
  9816. return WorkerPool;
  9817. }());
  9818. BABYLON.WorkerPool = WorkerPool;
  9819. })(BABYLON || (BABYLON = {}));
  9820. //# sourceMappingURL=babylon.workerPool.js.map
  9821. "use strict";
  9822. var BABYLON;
  9823. (function (BABYLON) {
  9824. var _AlphaState = /** @class */ (function () {
  9825. /**
  9826. * Initializes the state.
  9827. */
  9828. function _AlphaState() {
  9829. this._isAlphaBlendDirty = false;
  9830. this._isBlendFunctionParametersDirty = false;
  9831. this._isBlendEquationParametersDirty = false;
  9832. this._isBlendConstantsDirty = false;
  9833. this._alphaBlend = false;
  9834. this._blendFunctionParameters = new Array(4);
  9835. this._blendEquationParameters = new Array(2);
  9836. this._blendConstants = new Array(4);
  9837. this.reset();
  9838. }
  9839. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9840. get: function () {
  9841. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9842. },
  9843. enumerable: true,
  9844. configurable: true
  9845. });
  9846. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9847. get: function () {
  9848. return this._alphaBlend;
  9849. },
  9850. set: function (value) {
  9851. if (this._alphaBlend === value) {
  9852. return;
  9853. }
  9854. this._alphaBlend = value;
  9855. this._isAlphaBlendDirty = true;
  9856. },
  9857. enumerable: true,
  9858. configurable: true
  9859. });
  9860. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9861. if (this._blendConstants[0] === r &&
  9862. this._blendConstants[1] === g &&
  9863. this._blendConstants[2] === b &&
  9864. this._blendConstants[3] === a) {
  9865. return;
  9866. }
  9867. this._blendConstants[0] = r;
  9868. this._blendConstants[1] = g;
  9869. this._blendConstants[2] = b;
  9870. this._blendConstants[3] = a;
  9871. this._isBlendConstantsDirty = true;
  9872. };
  9873. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9874. if (this._blendFunctionParameters[0] === value0 &&
  9875. this._blendFunctionParameters[1] === value1 &&
  9876. this._blendFunctionParameters[2] === value2 &&
  9877. this._blendFunctionParameters[3] === value3) {
  9878. return;
  9879. }
  9880. this._blendFunctionParameters[0] = value0;
  9881. this._blendFunctionParameters[1] = value1;
  9882. this._blendFunctionParameters[2] = value2;
  9883. this._blendFunctionParameters[3] = value3;
  9884. this._isBlendFunctionParametersDirty = true;
  9885. };
  9886. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9887. if (this._blendEquationParameters[0] === rgb &&
  9888. this._blendEquationParameters[1] === alpha) {
  9889. return;
  9890. }
  9891. this._blendEquationParameters[0] = rgb;
  9892. this._blendEquationParameters[1] = alpha;
  9893. this._isBlendEquationParametersDirty = true;
  9894. };
  9895. _AlphaState.prototype.reset = function () {
  9896. this._alphaBlend = false;
  9897. this._blendFunctionParameters[0] = null;
  9898. this._blendFunctionParameters[1] = null;
  9899. this._blendFunctionParameters[2] = null;
  9900. this._blendFunctionParameters[3] = null;
  9901. this._blendEquationParameters[0] = null;
  9902. this._blendEquationParameters[1] = null;
  9903. this._blendConstants[0] = null;
  9904. this._blendConstants[1] = null;
  9905. this._blendConstants[2] = null;
  9906. this._blendConstants[3] = null;
  9907. this._isAlphaBlendDirty = true;
  9908. this._isBlendFunctionParametersDirty = false;
  9909. this._isBlendEquationParametersDirty = false;
  9910. this._isBlendConstantsDirty = false;
  9911. };
  9912. _AlphaState.prototype.apply = function (gl) {
  9913. if (!this.isDirty) {
  9914. return;
  9915. }
  9916. // Alpha blend
  9917. if (this._isAlphaBlendDirty) {
  9918. if (this._alphaBlend) {
  9919. gl.enable(gl.BLEND);
  9920. }
  9921. else {
  9922. gl.disable(gl.BLEND);
  9923. }
  9924. this._isAlphaBlendDirty = false;
  9925. }
  9926. // Alpha function
  9927. if (this._isBlendFunctionParametersDirty) {
  9928. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9929. this._isBlendFunctionParametersDirty = false;
  9930. }
  9931. // Alpha equation
  9932. if (this._isBlendEquationParametersDirty) {
  9933. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9934. this._isBlendEquationParametersDirty = false;
  9935. }
  9936. // Constants
  9937. if (this._isBlendConstantsDirty) {
  9938. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9939. this._isBlendConstantsDirty = false;
  9940. }
  9941. };
  9942. return _AlphaState;
  9943. }());
  9944. BABYLON._AlphaState = _AlphaState;
  9945. })(BABYLON || (BABYLON = {}));
  9946. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9947. "use strict";
  9948. var BABYLON;
  9949. (function (BABYLON) {
  9950. var _DepthCullingState = /** @class */ (function () {
  9951. /**
  9952. * Initializes the state.
  9953. */
  9954. function _DepthCullingState() {
  9955. this._isDepthTestDirty = false;
  9956. this._isDepthMaskDirty = false;
  9957. this._isDepthFuncDirty = false;
  9958. this._isCullFaceDirty = false;
  9959. this._isCullDirty = false;
  9960. this._isZOffsetDirty = false;
  9961. this._isFrontFaceDirty = false;
  9962. this.reset();
  9963. }
  9964. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9965. get: function () {
  9966. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9967. },
  9968. enumerable: true,
  9969. configurable: true
  9970. });
  9971. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9972. get: function () {
  9973. return this._zOffset;
  9974. },
  9975. set: function (value) {
  9976. if (this._zOffset === value) {
  9977. return;
  9978. }
  9979. this._zOffset = value;
  9980. this._isZOffsetDirty = true;
  9981. },
  9982. enumerable: true,
  9983. configurable: true
  9984. });
  9985. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9986. get: function () {
  9987. return this._cullFace;
  9988. },
  9989. set: function (value) {
  9990. if (this._cullFace === value) {
  9991. return;
  9992. }
  9993. this._cullFace = value;
  9994. this._isCullFaceDirty = true;
  9995. },
  9996. enumerable: true,
  9997. configurable: true
  9998. });
  9999. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10000. get: function () {
  10001. return this._cull;
  10002. },
  10003. set: function (value) {
  10004. if (this._cull === value) {
  10005. return;
  10006. }
  10007. this._cull = value;
  10008. this._isCullDirty = true;
  10009. },
  10010. enumerable: true,
  10011. configurable: true
  10012. });
  10013. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10014. get: function () {
  10015. return this._depthFunc;
  10016. },
  10017. set: function (value) {
  10018. if (this._depthFunc === value) {
  10019. return;
  10020. }
  10021. this._depthFunc = value;
  10022. this._isDepthFuncDirty = true;
  10023. },
  10024. enumerable: true,
  10025. configurable: true
  10026. });
  10027. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10028. get: function () {
  10029. return this._depthMask;
  10030. },
  10031. set: function (value) {
  10032. if (this._depthMask === value) {
  10033. return;
  10034. }
  10035. this._depthMask = value;
  10036. this._isDepthMaskDirty = true;
  10037. },
  10038. enumerable: true,
  10039. configurable: true
  10040. });
  10041. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10042. get: function () {
  10043. return this._depthTest;
  10044. },
  10045. set: function (value) {
  10046. if (this._depthTest === value) {
  10047. return;
  10048. }
  10049. this._depthTest = value;
  10050. this._isDepthTestDirty = true;
  10051. },
  10052. enumerable: true,
  10053. configurable: true
  10054. });
  10055. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10056. get: function () {
  10057. return this._frontFace;
  10058. },
  10059. set: function (value) {
  10060. if (this._frontFace === value) {
  10061. return;
  10062. }
  10063. this._frontFace = value;
  10064. this._isFrontFaceDirty = true;
  10065. },
  10066. enumerable: true,
  10067. configurable: true
  10068. });
  10069. _DepthCullingState.prototype.reset = function () {
  10070. this._depthMask = true;
  10071. this._depthTest = true;
  10072. this._depthFunc = null;
  10073. this._cullFace = null;
  10074. this._cull = null;
  10075. this._zOffset = 0;
  10076. this._frontFace = null;
  10077. this._isDepthTestDirty = true;
  10078. this._isDepthMaskDirty = true;
  10079. this._isDepthFuncDirty = false;
  10080. this._isCullFaceDirty = false;
  10081. this._isCullDirty = false;
  10082. this._isZOffsetDirty = false;
  10083. this._isFrontFaceDirty = false;
  10084. };
  10085. _DepthCullingState.prototype.apply = function (gl) {
  10086. if (!this.isDirty) {
  10087. return;
  10088. }
  10089. // Cull
  10090. if (this._isCullDirty) {
  10091. if (this.cull) {
  10092. gl.enable(gl.CULL_FACE);
  10093. }
  10094. else {
  10095. gl.disable(gl.CULL_FACE);
  10096. }
  10097. this._isCullDirty = false;
  10098. }
  10099. // Cull face
  10100. if (this._isCullFaceDirty) {
  10101. gl.cullFace(this.cullFace);
  10102. this._isCullFaceDirty = false;
  10103. }
  10104. // Depth mask
  10105. if (this._isDepthMaskDirty) {
  10106. gl.depthMask(this.depthMask);
  10107. this._isDepthMaskDirty = false;
  10108. }
  10109. // Depth test
  10110. if (this._isDepthTestDirty) {
  10111. if (this.depthTest) {
  10112. gl.enable(gl.DEPTH_TEST);
  10113. }
  10114. else {
  10115. gl.disable(gl.DEPTH_TEST);
  10116. }
  10117. this._isDepthTestDirty = false;
  10118. }
  10119. // Depth func
  10120. if (this._isDepthFuncDirty) {
  10121. gl.depthFunc(this.depthFunc);
  10122. this._isDepthFuncDirty = false;
  10123. }
  10124. // zOffset
  10125. if (this._isZOffsetDirty) {
  10126. if (this.zOffset) {
  10127. gl.enable(gl.POLYGON_OFFSET_FILL);
  10128. gl.polygonOffset(this.zOffset, 0);
  10129. }
  10130. else {
  10131. gl.disable(gl.POLYGON_OFFSET_FILL);
  10132. }
  10133. this._isZOffsetDirty = false;
  10134. }
  10135. // Front face
  10136. if (this._isFrontFaceDirty) {
  10137. gl.frontFace(this.frontFace);
  10138. this._isFrontFaceDirty = false;
  10139. }
  10140. };
  10141. return _DepthCullingState;
  10142. }());
  10143. BABYLON._DepthCullingState = _DepthCullingState;
  10144. })(BABYLON || (BABYLON = {}));
  10145. //# sourceMappingURL=babylon.depthCullingState.js.map
  10146. "use strict";
  10147. var BABYLON;
  10148. (function (BABYLON) {
  10149. var _StencilState = /** @class */ (function () {
  10150. function _StencilState() {
  10151. this._isStencilTestDirty = false;
  10152. this._isStencilMaskDirty = false;
  10153. this._isStencilFuncDirty = false;
  10154. this._isStencilOpDirty = false;
  10155. this.reset();
  10156. }
  10157. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10158. get: function () {
  10159. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10160. },
  10161. enumerable: true,
  10162. configurable: true
  10163. });
  10164. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10165. get: function () {
  10166. return this._stencilFunc;
  10167. },
  10168. set: function (value) {
  10169. if (this._stencilFunc === value) {
  10170. return;
  10171. }
  10172. this._stencilFunc = value;
  10173. this._isStencilFuncDirty = true;
  10174. },
  10175. enumerable: true,
  10176. configurable: true
  10177. });
  10178. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10179. get: function () {
  10180. return this._stencilFuncRef;
  10181. },
  10182. set: function (value) {
  10183. if (this._stencilFuncRef === value) {
  10184. return;
  10185. }
  10186. this._stencilFuncRef = value;
  10187. this._isStencilFuncDirty = true;
  10188. },
  10189. enumerable: true,
  10190. configurable: true
  10191. });
  10192. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10193. get: function () {
  10194. return this._stencilFuncMask;
  10195. },
  10196. set: function (value) {
  10197. if (this._stencilFuncMask === value) {
  10198. return;
  10199. }
  10200. this._stencilFuncMask = value;
  10201. this._isStencilFuncDirty = true;
  10202. },
  10203. enumerable: true,
  10204. configurable: true
  10205. });
  10206. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10207. get: function () {
  10208. return this._stencilOpStencilFail;
  10209. },
  10210. set: function (value) {
  10211. if (this._stencilOpStencilFail === value) {
  10212. return;
  10213. }
  10214. this._stencilOpStencilFail = value;
  10215. this._isStencilOpDirty = true;
  10216. },
  10217. enumerable: true,
  10218. configurable: true
  10219. });
  10220. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10221. get: function () {
  10222. return this._stencilOpDepthFail;
  10223. },
  10224. set: function (value) {
  10225. if (this._stencilOpDepthFail === value) {
  10226. return;
  10227. }
  10228. this._stencilOpDepthFail = value;
  10229. this._isStencilOpDirty = true;
  10230. },
  10231. enumerable: true,
  10232. configurable: true
  10233. });
  10234. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10235. get: function () {
  10236. return this._stencilOpStencilDepthPass;
  10237. },
  10238. set: function (value) {
  10239. if (this._stencilOpStencilDepthPass === value) {
  10240. return;
  10241. }
  10242. this._stencilOpStencilDepthPass = value;
  10243. this._isStencilOpDirty = true;
  10244. },
  10245. enumerable: true,
  10246. configurable: true
  10247. });
  10248. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10249. get: function () {
  10250. return this._stencilMask;
  10251. },
  10252. set: function (value) {
  10253. if (this._stencilMask === value) {
  10254. return;
  10255. }
  10256. this._stencilMask = value;
  10257. this._isStencilMaskDirty = true;
  10258. },
  10259. enumerable: true,
  10260. configurable: true
  10261. });
  10262. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10263. get: function () {
  10264. return this._stencilTest;
  10265. },
  10266. set: function (value) {
  10267. if (this._stencilTest === value) {
  10268. return;
  10269. }
  10270. this._stencilTest = value;
  10271. this._isStencilTestDirty = true;
  10272. },
  10273. enumerable: true,
  10274. configurable: true
  10275. });
  10276. _StencilState.prototype.reset = function () {
  10277. this._stencilTest = false;
  10278. this._stencilMask = 0xFF;
  10279. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10280. this._stencilFuncRef = 1;
  10281. this._stencilFuncMask = 0xFF;
  10282. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10283. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10284. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10285. this._isStencilTestDirty = true;
  10286. this._isStencilMaskDirty = true;
  10287. this._isStencilFuncDirty = true;
  10288. this._isStencilOpDirty = true;
  10289. };
  10290. _StencilState.prototype.apply = function (gl) {
  10291. if (!this.isDirty) {
  10292. return;
  10293. }
  10294. // Stencil test
  10295. if (this._isStencilTestDirty) {
  10296. if (this.stencilTest) {
  10297. gl.enable(gl.STENCIL_TEST);
  10298. }
  10299. else {
  10300. gl.disable(gl.STENCIL_TEST);
  10301. }
  10302. this._isStencilTestDirty = false;
  10303. }
  10304. // Stencil mask
  10305. if (this._isStencilMaskDirty) {
  10306. gl.stencilMask(this.stencilMask);
  10307. this._isStencilMaskDirty = false;
  10308. }
  10309. // Stencil func
  10310. if (this._isStencilFuncDirty) {
  10311. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10312. this._isStencilFuncDirty = false;
  10313. }
  10314. // Stencil op
  10315. if (this._isStencilOpDirty) {
  10316. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10317. this._isStencilOpDirty = false;
  10318. }
  10319. };
  10320. return _StencilState;
  10321. }());
  10322. BABYLON._StencilState = _StencilState;
  10323. })(BABYLON || (BABYLON = {}));
  10324. //# sourceMappingURL=babylon.stencilState.js.map
  10325. "use strict";
  10326. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10327. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10328. s = arguments[i];
  10329. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10330. t[p] = s[p];
  10331. }
  10332. return t;
  10333. };
  10334. var BABYLON;
  10335. (function (BABYLON) {
  10336. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10337. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10338. };
  10339. var compileRawShader = function (gl, source, type) {
  10340. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10341. gl.shaderSource(shader, source);
  10342. gl.compileShader(shader);
  10343. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10344. var log = gl.getShaderInfoLog(shader);
  10345. if (log) {
  10346. throw new Error(log);
  10347. }
  10348. }
  10349. if (!shader) {
  10350. throw new Error("Something went wrong while compile the shader.");
  10351. }
  10352. return shader;
  10353. };
  10354. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10355. var magFilter = gl.NEAREST;
  10356. var minFilter = gl.NEAREST;
  10357. switch (samplingMode) {
  10358. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10359. magFilter = gl.LINEAR;
  10360. if (generateMipMaps) {
  10361. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10362. }
  10363. else {
  10364. minFilter = gl.LINEAR;
  10365. }
  10366. break;
  10367. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10368. magFilter = gl.LINEAR;
  10369. if (generateMipMaps) {
  10370. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10371. }
  10372. else {
  10373. minFilter = gl.LINEAR;
  10374. }
  10375. break;
  10376. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10377. magFilter = gl.NEAREST;
  10378. if (generateMipMaps) {
  10379. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10380. }
  10381. else {
  10382. minFilter = gl.NEAREST;
  10383. }
  10384. break;
  10385. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10386. magFilter = gl.NEAREST;
  10387. if (generateMipMaps) {
  10388. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10389. }
  10390. else {
  10391. minFilter = gl.NEAREST;
  10392. }
  10393. break;
  10394. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10395. magFilter = gl.NEAREST;
  10396. if (generateMipMaps) {
  10397. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10398. }
  10399. else {
  10400. minFilter = gl.LINEAR;
  10401. }
  10402. break;
  10403. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10404. magFilter = gl.NEAREST;
  10405. if (generateMipMaps) {
  10406. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10407. }
  10408. else {
  10409. minFilter = gl.LINEAR;
  10410. }
  10411. break;
  10412. case BABYLON.Texture.NEAREST_LINEAR:
  10413. magFilter = gl.NEAREST;
  10414. minFilter = gl.LINEAR;
  10415. break;
  10416. case BABYLON.Texture.NEAREST_NEAREST:
  10417. magFilter = gl.NEAREST;
  10418. minFilter = gl.NEAREST;
  10419. break;
  10420. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10421. magFilter = gl.LINEAR;
  10422. if (generateMipMaps) {
  10423. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10424. }
  10425. else {
  10426. minFilter = gl.NEAREST;
  10427. }
  10428. break;
  10429. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10430. magFilter = gl.LINEAR;
  10431. if (generateMipMaps) {
  10432. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10433. }
  10434. else {
  10435. minFilter = gl.NEAREST;
  10436. }
  10437. break;
  10438. case BABYLON.Texture.LINEAR_LINEAR:
  10439. magFilter = gl.LINEAR;
  10440. minFilter = gl.LINEAR;
  10441. break;
  10442. case BABYLON.Texture.LINEAR_NEAREST:
  10443. magFilter = gl.LINEAR;
  10444. minFilter = gl.NEAREST;
  10445. break;
  10446. }
  10447. return {
  10448. min: minFilter,
  10449. mag: magFilter
  10450. };
  10451. };
  10452. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10453. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10454. var img;
  10455. var onload = function () {
  10456. loadedImages[index] = img;
  10457. loadedImages._internalCount++;
  10458. if (scene) {
  10459. scene._removePendingData(img);
  10460. }
  10461. if (loadedImages._internalCount === 6) {
  10462. onfinish(loadedImages);
  10463. }
  10464. };
  10465. var onerror = function (message, exception) {
  10466. if (scene) {
  10467. scene._removePendingData(img);
  10468. }
  10469. if (onErrorCallBack) {
  10470. onErrorCallBack(message, exception);
  10471. }
  10472. };
  10473. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10474. if (scene) {
  10475. scene._addPendingData(img);
  10476. }
  10477. };
  10478. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10479. if (onError === void 0) { onError = null; }
  10480. var loadedImages = [];
  10481. loadedImages._internalCount = 0;
  10482. for (var index = 0; index < 6; index++) {
  10483. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10484. }
  10485. };
  10486. var BufferPointer = /** @class */ (function () {
  10487. function BufferPointer() {
  10488. }
  10489. return BufferPointer;
  10490. }());
  10491. var InstancingAttributeInfo = /** @class */ (function () {
  10492. function InstancingAttributeInfo() {
  10493. }
  10494. return InstancingAttributeInfo;
  10495. }());
  10496. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10497. /**
  10498. * Define options used to create a render target texture
  10499. */
  10500. var RenderTargetCreationOptions = /** @class */ (function () {
  10501. function RenderTargetCreationOptions() {
  10502. }
  10503. return RenderTargetCreationOptions;
  10504. }());
  10505. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10506. /**
  10507. * Define options used to create a depth texture
  10508. */
  10509. var DepthTextureCreationOptions = /** @class */ (function () {
  10510. function DepthTextureCreationOptions() {
  10511. }
  10512. return DepthTextureCreationOptions;
  10513. }());
  10514. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10515. /**
  10516. * Regroup several parameters relative to the browser in use
  10517. */
  10518. var EngineCapabilities = /** @class */ (function () {
  10519. function EngineCapabilities() {
  10520. }
  10521. return EngineCapabilities;
  10522. }());
  10523. BABYLON.EngineCapabilities = EngineCapabilities;
  10524. /**
  10525. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10526. */
  10527. var Engine = /** @class */ (function () {
  10528. /**
  10529. * @constructor
  10530. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10531. * @param antialias defines enable antialiasing (default: false)
  10532. * @param options defines further options to be sent to the getContext() function
  10533. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10534. */
  10535. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10536. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10537. var _this = this;
  10538. // Public members
  10539. this.forcePOTTextures = false;
  10540. this.isFullscreen = false;
  10541. this.isPointerLock = false;
  10542. this.cullBackFaces = true;
  10543. this.renderEvenInBackground = true;
  10544. this.preventCacheWipeBetweenFrames = false;
  10545. // To enable/disable IDB support and avoid XHR on .manifest
  10546. this.enableOfflineSupport = false;
  10547. this.scenes = new Array();
  10548. this.postProcesses = new Array();
  10549. // Observables
  10550. /**
  10551. * Observable event triggered each time the rendering canvas is resized
  10552. */
  10553. this.onResizeObservable = new BABYLON.Observable();
  10554. /**
  10555. * Observable event triggered each time the canvas loses focus
  10556. */
  10557. this.onCanvasBlurObservable = new BABYLON.Observable();
  10558. /**
  10559. * Observable event triggered each time the canvas gains focus
  10560. */
  10561. this.onCanvasFocusObservable = new BABYLON.Observable();
  10562. /**
  10563. * Observable event triggered each time the canvas receives pointerout event
  10564. */
  10565. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10566. /**
  10567. * Observable event triggered before each texture is initialized
  10568. */
  10569. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10570. //WebVR
  10571. this._vrDisplay = undefined;
  10572. this._vrSupported = false;
  10573. this._vrExclusivePointerMode = false;
  10574. // Uniform buffers list
  10575. this.disableUniformBuffers = false;
  10576. this._uniformBuffers = new Array();
  10577. // Observables
  10578. /**
  10579. * Observable raised when the engine begins a new frame
  10580. */
  10581. this.onBeginFrameObservable = new BABYLON.Observable();
  10582. /**
  10583. * Observable raised when the engine ends the current frame
  10584. */
  10585. this.onEndFrameObservable = new BABYLON.Observable();
  10586. /**
  10587. * Observable raised when the engine is about to compile a shader
  10588. */
  10589. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10590. /**
  10591. * Observable raised when the engine has jsut compiled a shader
  10592. */
  10593. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10594. this._windowIsBackground = false;
  10595. this._webGLVersion = 1.0;
  10596. this._badOS = false;
  10597. this._badDesktopOS = false;
  10598. /**
  10599. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10600. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10601. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10602. */
  10603. this.disableTextureBindingOptimization = false;
  10604. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10605. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10606. this.onVRRequestPresentStart = new BABYLON.Observable();
  10607. this._colorWrite = true;
  10608. this._drawCalls = new BABYLON.PerfCounter();
  10609. this._textureCollisions = new BABYLON.PerfCounter();
  10610. this._renderingQueueLaunched = false;
  10611. this._activeRenderLoops = new Array();
  10612. // Deterministic lockstepMaxSteps
  10613. this._deterministicLockstep = false;
  10614. this._lockstepMaxSteps = 4;
  10615. // Lost context
  10616. this.onContextLostObservable = new BABYLON.Observable();
  10617. this.onContextRestoredObservable = new BABYLON.Observable();
  10618. this._contextWasLost = false;
  10619. this._doNotHandleContextLost = false;
  10620. // FPS
  10621. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10622. this._fps = 60;
  10623. this._deltaTime = 0;
  10624. /**
  10625. * Turn this value on if you want to pause FPS computation when in background
  10626. */
  10627. this.disablePerformanceMonitorInBackground = false;
  10628. // States
  10629. this._depthCullingState = new BABYLON._DepthCullingState();
  10630. this._stencilState = new BABYLON._StencilState();
  10631. this._alphaState = new BABYLON._AlphaState();
  10632. this._alphaMode = Engine.ALPHA_DISABLE;
  10633. // Cache
  10634. this._internalTexturesCache = new Array();
  10635. this._activeChannel = 0;
  10636. this._currentTextureChannel = -1;
  10637. this._boundTexturesCache = {};
  10638. this._compiledEffects = {};
  10639. this._vertexAttribArraysEnabled = [];
  10640. this._uintIndicesCurrentlySet = false;
  10641. this._currentBoundBuffer = new Array();
  10642. this._currentBufferPointers = new Array();
  10643. this._currentInstanceLocations = new Array();
  10644. this._currentInstanceBuffers = new Array();
  10645. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10646. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10647. this._vaoRecordInProgress = false;
  10648. this._mustWipeVertexAttributes = false;
  10649. this._nextFreeTextureSlots = new Array();
  10650. this._maxSimultaneousTextures = 0;
  10651. this._activeRequests = new Array();
  10652. // Hardware supported Compressed Textures
  10653. this._texturesSupported = new Array();
  10654. this._onVRFullScreenTriggered = function () {
  10655. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10656. //get the old size before we change
  10657. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10658. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10659. //get the width and height, change the render size
  10660. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10661. _this.setHardwareScalingLevel(1);
  10662. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10663. }
  10664. else {
  10665. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10666. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10667. }
  10668. };
  10669. this._boundUniforms = {};
  10670. // Register promises
  10671. BABYLON.PromisePolyfill.Apply();
  10672. var canvas = null;
  10673. Engine.Instances.push(this);
  10674. if (!canvasOrContext) {
  10675. return;
  10676. }
  10677. options = options || {};
  10678. if (canvasOrContext.getContext) {
  10679. canvas = canvasOrContext;
  10680. this._renderingCanvas = canvas;
  10681. if (antialias != null) {
  10682. options.antialias = antialias;
  10683. }
  10684. if (options.deterministicLockstep === undefined) {
  10685. options.deterministicLockstep = false;
  10686. }
  10687. if (options.lockstepMaxSteps === undefined) {
  10688. options.lockstepMaxSteps = 4;
  10689. }
  10690. if (options.preserveDrawingBuffer === undefined) {
  10691. options.preserveDrawingBuffer = false;
  10692. }
  10693. if (options.audioEngine === undefined) {
  10694. options.audioEngine = true;
  10695. }
  10696. if (options.stencil === undefined) {
  10697. options.stencil = true;
  10698. }
  10699. this._deterministicLockstep = options.deterministicLockstep;
  10700. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10701. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10702. // Exceptions
  10703. if (navigator && navigator.userAgent) {
  10704. var ua = navigator.userAgent;
  10705. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10706. var exception = _a[_i];
  10707. var key = exception.key;
  10708. var targets = exception.targets;
  10709. if (ua.indexOf(key) > -1) {
  10710. if (exception.capture && exception.captureConstraint) {
  10711. var capture = exception.capture;
  10712. var constraint = exception.captureConstraint;
  10713. var regex = new RegExp(capture);
  10714. var matches = regex.exec(ua);
  10715. if (matches && matches.length > 0) {
  10716. var capturedValue = parseInt(matches[matches.length - 1]);
  10717. if (capturedValue >= constraint) {
  10718. continue;
  10719. }
  10720. }
  10721. }
  10722. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10723. var target = targets_1[_b];
  10724. switch (target) {
  10725. case "uniformBuffer":
  10726. this.disableUniformBuffers = true;
  10727. break;
  10728. case "textureBindingOptimization":
  10729. this.disableTextureBindingOptimization = true;
  10730. break;
  10731. }
  10732. }
  10733. }
  10734. }
  10735. }
  10736. // GL
  10737. if (!options.disableWebGL2Support) {
  10738. try {
  10739. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10740. if (this._gl) {
  10741. this._webGLVersion = 2.0;
  10742. }
  10743. }
  10744. catch (e) {
  10745. // Do nothing
  10746. }
  10747. }
  10748. if (!this._gl) {
  10749. if (!canvas) {
  10750. throw new Error("The provided canvas is null or undefined.");
  10751. }
  10752. try {
  10753. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10754. }
  10755. catch (e) {
  10756. throw new Error("WebGL not supported");
  10757. }
  10758. }
  10759. if (!this._gl) {
  10760. throw new Error("WebGL not supported");
  10761. }
  10762. this._onCanvasFocus = function () {
  10763. _this.onCanvasFocusObservable.notifyObservers(_this);
  10764. };
  10765. this._onCanvasBlur = function () {
  10766. _this.onCanvasBlurObservable.notifyObservers(_this);
  10767. };
  10768. canvas.addEventListener("focus", this._onCanvasFocus);
  10769. canvas.addEventListener("blur", this._onCanvasBlur);
  10770. this._onBlur = function () {
  10771. if (_this.disablePerformanceMonitorInBackground) {
  10772. _this._performanceMonitor.disable();
  10773. }
  10774. _this._windowIsBackground = true;
  10775. };
  10776. this._onFocus = function () {
  10777. if (_this.disablePerformanceMonitorInBackground) {
  10778. _this._performanceMonitor.enable();
  10779. }
  10780. _this._windowIsBackground = false;
  10781. };
  10782. this._onCanvasPointerOut = function (ev) {
  10783. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10784. };
  10785. window.addEventListener("blur", this._onBlur);
  10786. window.addEventListener("focus", this._onFocus);
  10787. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10788. // Context lost
  10789. if (!this._doNotHandleContextLost) {
  10790. this._onContextLost = function (evt) {
  10791. evt.preventDefault();
  10792. _this._contextWasLost = true;
  10793. BABYLON.Tools.Warn("WebGL context lost.");
  10794. _this.onContextLostObservable.notifyObservers(_this);
  10795. };
  10796. this._onContextRestored = function (evt) {
  10797. // Adding a timeout to avoid race condition at browser level
  10798. setTimeout(function () {
  10799. // Rebuild gl context
  10800. _this._initGLContext();
  10801. // Rebuild effects
  10802. _this._rebuildEffects();
  10803. // Rebuild textures
  10804. _this._rebuildInternalTextures();
  10805. // Rebuild buffers
  10806. _this._rebuildBuffers();
  10807. // Cache
  10808. _this.wipeCaches(true);
  10809. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10810. _this.onContextRestoredObservable.notifyObservers(_this);
  10811. _this._contextWasLost = false;
  10812. }, 0);
  10813. };
  10814. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10815. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10816. }
  10817. }
  10818. else {
  10819. this._gl = canvasOrContext;
  10820. this._renderingCanvas = this._gl.canvas;
  10821. if (this._gl.renderbufferStorageMultisample) {
  10822. this._webGLVersion = 2.0;
  10823. }
  10824. options.stencil = this._gl.getContextAttributes().stencil;
  10825. }
  10826. // Viewport
  10827. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10828. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10829. this.resize();
  10830. this._isStencilEnable = options.stencil ? true : false;
  10831. this._initGLContext();
  10832. if (canvas) {
  10833. // Fullscreen
  10834. this._onFullscreenChange = function () {
  10835. if (document.fullscreen !== undefined) {
  10836. _this.isFullscreen = document.fullscreen;
  10837. }
  10838. else if (document.mozFullScreen !== undefined) {
  10839. _this.isFullscreen = document.mozFullScreen;
  10840. }
  10841. else if (document.webkitIsFullScreen !== undefined) {
  10842. _this.isFullscreen = document.webkitIsFullScreen;
  10843. }
  10844. else if (document.msIsFullScreen !== undefined) {
  10845. _this.isFullscreen = document.msIsFullScreen;
  10846. }
  10847. // Pointer lock
  10848. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10849. canvas.requestPointerLock = canvas.requestPointerLock ||
  10850. canvas.msRequestPointerLock ||
  10851. canvas.mozRequestPointerLock ||
  10852. canvas.webkitRequestPointerLock;
  10853. if (canvas.requestPointerLock) {
  10854. canvas.requestPointerLock();
  10855. }
  10856. }
  10857. };
  10858. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10859. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10860. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10861. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10862. // Pointer lock
  10863. this._onPointerLockChange = function () {
  10864. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10865. document.webkitPointerLockElement === canvas ||
  10866. document.msPointerLockElement === canvas ||
  10867. document.pointerLockElement === canvas);
  10868. };
  10869. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10870. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10871. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10872. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10873. this._onVRDisplayPointerRestricted = function () {
  10874. if (canvas) {
  10875. canvas.requestPointerLock();
  10876. }
  10877. };
  10878. this._onVRDisplayPointerUnrestricted = function () {
  10879. document.exitPointerLock();
  10880. };
  10881. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10882. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10883. }
  10884. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10885. Engine.audioEngine = new BABYLON.AudioEngine();
  10886. }
  10887. // Prepare buffer pointers
  10888. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10889. this._currentBufferPointers[i] = new BufferPointer();
  10890. }
  10891. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10892. // Load WebVR Devices
  10893. if (options.autoEnableWebVR) {
  10894. this.initWebVR();
  10895. }
  10896. // Detect if we are running on a faulty buggy OS.
  10897. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10898. // Detect if we are running on a faulty buggy desktop OS.
  10899. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10900. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10901. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10902. }
  10903. Object.defineProperty(Engine, "LastCreatedEngine", {
  10904. get: function () {
  10905. if (Engine.Instances.length === 0) {
  10906. return null;
  10907. }
  10908. return Engine.Instances[Engine.Instances.length - 1];
  10909. },
  10910. enumerable: true,
  10911. configurable: true
  10912. });
  10913. Object.defineProperty(Engine, "LastCreatedScene", {
  10914. get: function () {
  10915. var lastCreatedEngine = Engine.LastCreatedEngine;
  10916. if (!lastCreatedEngine) {
  10917. return null;
  10918. }
  10919. if (lastCreatedEngine.scenes.length === 0) {
  10920. return null;
  10921. }
  10922. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10923. },
  10924. enumerable: true,
  10925. configurable: true
  10926. });
  10927. /**
  10928. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10929. */
  10930. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10931. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10932. var engine = Engine.Instances[engineIndex];
  10933. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10934. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10935. }
  10936. }
  10937. };
  10938. Object.defineProperty(Engine, "NEVER", {
  10939. get: function () {
  10940. return Engine._NEVER;
  10941. },
  10942. enumerable: true,
  10943. configurable: true
  10944. });
  10945. Object.defineProperty(Engine, "ALWAYS", {
  10946. get: function () {
  10947. return Engine._ALWAYS;
  10948. },
  10949. enumerable: true,
  10950. configurable: true
  10951. });
  10952. Object.defineProperty(Engine, "LESS", {
  10953. get: function () {
  10954. return Engine._LESS;
  10955. },
  10956. enumerable: true,
  10957. configurable: true
  10958. });
  10959. Object.defineProperty(Engine, "EQUAL", {
  10960. get: function () {
  10961. return Engine._EQUAL;
  10962. },
  10963. enumerable: true,
  10964. configurable: true
  10965. });
  10966. Object.defineProperty(Engine, "LEQUAL", {
  10967. get: function () {
  10968. return Engine._LEQUAL;
  10969. },
  10970. enumerable: true,
  10971. configurable: true
  10972. });
  10973. Object.defineProperty(Engine, "GREATER", {
  10974. get: function () {
  10975. return Engine._GREATER;
  10976. },
  10977. enumerable: true,
  10978. configurable: true
  10979. });
  10980. Object.defineProperty(Engine, "GEQUAL", {
  10981. get: function () {
  10982. return Engine._GEQUAL;
  10983. },
  10984. enumerable: true,
  10985. configurable: true
  10986. });
  10987. Object.defineProperty(Engine, "NOTEQUAL", {
  10988. get: function () {
  10989. return Engine._NOTEQUAL;
  10990. },
  10991. enumerable: true,
  10992. configurable: true
  10993. });
  10994. Object.defineProperty(Engine, "KEEP", {
  10995. get: function () {
  10996. return Engine._KEEP;
  10997. },
  10998. enumerable: true,
  10999. configurable: true
  11000. });
  11001. Object.defineProperty(Engine, "REPLACE", {
  11002. get: function () {
  11003. return Engine._REPLACE;
  11004. },
  11005. enumerable: true,
  11006. configurable: true
  11007. });
  11008. Object.defineProperty(Engine, "INCR", {
  11009. get: function () {
  11010. return Engine._INCR;
  11011. },
  11012. enumerable: true,
  11013. configurable: true
  11014. });
  11015. Object.defineProperty(Engine, "DECR", {
  11016. get: function () {
  11017. return Engine._DECR;
  11018. },
  11019. enumerable: true,
  11020. configurable: true
  11021. });
  11022. Object.defineProperty(Engine, "INVERT", {
  11023. get: function () {
  11024. return Engine._INVERT;
  11025. },
  11026. enumerable: true,
  11027. configurable: true
  11028. });
  11029. Object.defineProperty(Engine, "INCR_WRAP", {
  11030. get: function () {
  11031. return Engine._INCR_WRAP;
  11032. },
  11033. enumerable: true,
  11034. configurable: true
  11035. });
  11036. Object.defineProperty(Engine, "DECR_WRAP", {
  11037. get: function () {
  11038. return Engine._DECR_WRAP;
  11039. },
  11040. enumerable: true,
  11041. configurable: true
  11042. });
  11043. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11044. get: function () {
  11045. return Engine._ALPHA_DISABLE;
  11046. },
  11047. enumerable: true,
  11048. configurable: true
  11049. });
  11050. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11051. get: function () {
  11052. return Engine._ALPHA_ONEONE;
  11053. },
  11054. enumerable: true,
  11055. configurable: true
  11056. });
  11057. Object.defineProperty(Engine, "ALPHA_ADD", {
  11058. get: function () {
  11059. return Engine._ALPHA_ADD;
  11060. },
  11061. enumerable: true,
  11062. configurable: true
  11063. });
  11064. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11065. get: function () {
  11066. return Engine._ALPHA_COMBINE;
  11067. },
  11068. enumerable: true,
  11069. configurable: true
  11070. });
  11071. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11072. get: function () {
  11073. return Engine._ALPHA_SUBTRACT;
  11074. },
  11075. enumerable: true,
  11076. configurable: true
  11077. });
  11078. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11079. get: function () {
  11080. return Engine._ALPHA_MULTIPLY;
  11081. },
  11082. enumerable: true,
  11083. configurable: true
  11084. });
  11085. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11086. get: function () {
  11087. return Engine._ALPHA_MAXIMIZED;
  11088. },
  11089. enumerable: true,
  11090. configurable: true
  11091. });
  11092. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11093. get: function () {
  11094. return Engine._ALPHA_PREMULTIPLIED;
  11095. },
  11096. enumerable: true,
  11097. configurable: true
  11098. });
  11099. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11100. get: function () {
  11101. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11102. },
  11103. enumerable: true,
  11104. configurable: true
  11105. });
  11106. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11107. get: function () {
  11108. return Engine._ALPHA_INTERPOLATE;
  11109. },
  11110. enumerable: true,
  11111. configurable: true
  11112. });
  11113. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11114. get: function () {
  11115. return Engine._ALPHA_SCREENMODE;
  11116. },
  11117. enumerable: true,
  11118. configurable: true
  11119. });
  11120. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11121. get: function () {
  11122. return Engine._DELAYLOADSTATE_NONE;
  11123. },
  11124. enumerable: true,
  11125. configurable: true
  11126. });
  11127. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11128. get: function () {
  11129. return Engine._DELAYLOADSTATE_LOADED;
  11130. },
  11131. enumerable: true,
  11132. configurable: true
  11133. });
  11134. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11135. get: function () {
  11136. return Engine._DELAYLOADSTATE_LOADING;
  11137. },
  11138. enumerable: true,
  11139. configurable: true
  11140. });
  11141. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11142. get: function () {
  11143. return Engine._DELAYLOADSTATE_NOTLOADED;
  11144. },
  11145. enumerable: true,
  11146. configurable: true
  11147. });
  11148. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11149. get: function () {
  11150. return Engine._TEXTUREFORMAT_ALPHA;
  11151. },
  11152. enumerable: true,
  11153. configurable: true
  11154. });
  11155. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11156. get: function () {
  11157. return Engine._TEXTUREFORMAT_LUMINANCE;
  11158. },
  11159. enumerable: true,
  11160. configurable: true
  11161. });
  11162. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11163. /**
  11164. * R32F
  11165. */
  11166. get: function () {
  11167. return Engine._TEXTUREFORMAT_R32F;
  11168. },
  11169. enumerable: true,
  11170. configurable: true
  11171. });
  11172. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11173. /**
  11174. * RG32F
  11175. */
  11176. get: function () {
  11177. return Engine._TEXTUREFORMAT_RG32F;
  11178. },
  11179. enumerable: true,
  11180. configurable: true
  11181. });
  11182. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11183. /**
  11184. * RGB32F
  11185. */
  11186. get: function () {
  11187. return Engine._TEXTUREFORMAT_RGB32F;
  11188. },
  11189. enumerable: true,
  11190. configurable: true
  11191. });
  11192. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11193. /**
  11194. * RGBA32F
  11195. */
  11196. get: function () {
  11197. return Engine._TEXTUREFORMAT_RGBA32F;
  11198. },
  11199. enumerable: true,
  11200. configurable: true
  11201. });
  11202. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11203. get: function () {
  11204. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11205. },
  11206. enumerable: true,
  11207. configurable: true
  11208. });
  11209. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11210. get: function () {
  11211. return Engine._TEXTUREFORMAT_RGB;
  11212. },
  11213. enumerable: true,
  11214. configurable: true
  11215. });
  11216. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11217. get: function () {
  11218. return Engine._TEXTUREFORMAT_RGBA;
  11219. },
  11220. enumerable: true,
  11221. configurable: true
  11222. });
  11223. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11224. get: function () {
  11225. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11226. },
  11227. enumerable: true,
  11228. configurable: true
  11229. });
  11230. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11231. get: function () {
  11232. return Engine._TEXTURETYPE_FLOAT;
  11233. },
  11234. enumerable: true,
  11235. configurable: true
  11236. });
  11237. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11238. get: function () {
  11239. return Engine._TEXTURETYPE_HALF_FLOAT;
  11240. },
  11241. enumerable: true,
  11242. configurable: true
  11243. });
  11244. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11245. get: function () {
  11246. return Engine._SCALEMODE_FLOOR;
  11247. },
  11248. enumerable: true,
  11249. configurable: true
  11250. });
  11251. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11252. get: function () {
  11253. return Engine._SCALEMODE_NEAREST;
  11254. },
  11255. enumerable: true,
  11256. configurable: true
  11257. });
  11258. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11259. get: function () {
  11260. return Engine._SCALEMODE_CEILING;
  11261. },
  11262. enumerable: true,
  11263. configurable: true
  11264. });
  11265. Object.defineProperty(Engine, "Version", {
  11266. get: function () {
  11267. return "3.2.0-beta.1";
  11268. },
  11269. enumerable: true,
  11270. configurable: true
  11271. });
  11272. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11273. get: function () {
  11274. return this._vrExclusivePointerMode;
  11275. },
  11276. enumerable: true,
  11277. configurable: true
  11278. });
  11279. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11280. get: function () {
  11281. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11282. },
  11283. enumerable: true,
  11284. configurable: true
  11285. });
  11286. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11287. get: function () {
  11288. return this._webGLVersion < 2 || this.forcePOTTextures;
  11289. },
  11290. enumerable: true,
  11291. configurable: true
  11292. });
  11293. Object.defineProperty(Engine.prototype, "badOS", {
  11294. get: function () {
  11295. return this._badOS;
  11296. },
  11297. enumerable: true,
  11298. configurable: true
  11299. });
  11300. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11301. get: function () {
  11302. return this._badDesktopOS;
  11303. },
  11304. enumerable: true,
  11305. configurable: true
  11306. });
  11307. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11308. get: function () {
  11309. return this._performanceMonitor;
  11310. },
  11311. enumerable: true,
  11312. configurable: true
  11313. });
  11314. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11315. get: function () {
  11316. return this._texturesSupported;
  11317. },
  11318. enumerable: true,
  11319. configurable: true
  11320. });
  11321. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11322. get: function () {
  11323. return this._textureFormatInUse;
  11324. },
  11325. enumerable: true,
  11326. configurable: true
  11327. });
  11328. Object.defineProperty(Engine.prototype, "currentViewport", {
  11329. get: function () {
  11330. return this._cachedViewport;
  11331. },
  11332. enumerable: true,
  11333. configurable: true
  11334. });
  11335. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11336. // Empty texture
  11337. get: function () {
  11338. if (!this._emptyTexture) {
  11339. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11340. }
  11341. return this._emptyTexture;
  11342. },
  11343. enumerable: true,
  11344. configurable: true
  11345. });
  11346. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11347. get: function () {
  11348. if (!this._emptyTexture3D) {
  11349. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11350. }
  11351. return this._emptyTexture3D;
  11352. },
  11353. enumerable: true,
  11354. configurable: true
  11355. });
  11356. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11357. get: function () {
  11358. if (!this._emptyCubeTexture) {
  11359. var faceData = new Uint8Array(4);
  11360. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11361. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11362. }
  11363. return this._emptyCubeTexture;
  11364. },
  11365. enumerable: true,
  11366. configurable: true
  11367. });
  11368. Engine.prototype._rebuildInternalTextures = function () {
  11369. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11370. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11371. var internalTexture = currentState_1[_i];
  11372. internalTexture._rebuild();
  11373. }
  11374. };
  11375. Engine.prototype._rebuildEffects = function () {
  11376. for (var key in this._compiledEffects) {
  11377. var effect = this._compiledEffects[key];
  11378. effect._prepareEffect();
  11379. }
  11380. BABYLON.Effect.ResetCache();
  11381. };
  11382. Engine.prototype._rebuildBuffers = function () {
  11383. // Index / Vertex
  11384. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11385. var scene = _a[_i];
  11386. scene.resetCachedMaterial();
  11387. scene._rebuildGeometries();
  11388. scene._rebuildTextures();
  11389. }
  11390. // Uniforms
  11391. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11392. var uniformBuffer = _c[_b];
  11393. uniformBuffer._rebuild();
  11394. }
  11395. };
  11396. Engine.prototype._initGLContext = function () {
  11397. // Caps
  11398. this._caps = new EngineCapabilities();
  11399. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11400. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11401. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11402. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11403. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11404. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11405. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11406. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11407. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11408. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11409. // Infos
  11410. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11411. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11412. if (rendererInfo != null) {
  11413. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11414. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11415. }
  11416. if (!this._glVendor) {
  11417. this._glVendor = "Unknown vendor";
  11418. }
  11419. if (!this._glRenderer) {
  11420. this._glRenderer = "Unknown renderer";
  11421. }
  11422. // Constants
  11423. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11424. if (this._gl.RGBA16F !== 0x881A) {
  11425. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11426. }
  11427. if (this._gl.RGBA32F !== 0x8814) {
  11428. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11429. }
  11430. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11431. this._gl.DEPTH24_STENCIL8 = 35056;
  11432. }
  11433. // Extensions
  11434. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11435. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11436. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11437. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11438. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11439. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11440. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11441. 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');
  11442. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11443. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11444. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11445. this._caps.highPrecisionShaderSupported = true;
  11446. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11447. if (this._caps.timerQuery) {
  11448. if (this._webGLVersion === 1) {
  11449. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11450. }
  11451. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11452. }
  11453. // Checks if some of the format renders first to allow the use of webgl inspector.
  11454. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11455. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11456. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11457. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11458. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11459. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11460. if (this._webGLVersion > 1) {
  11461. this._gl.HALF_FLOAT_OES = 0x140B;
  11462. }
  11463. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11464. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11465. // Draw buffers
  11466. if (this._webGLVersion > 1) {
  11467. this._caps.drawBuffersExtension = true;
  11468. }
  11469. else {
  11470. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11471. if (drawBuffersExtension !== null) {
  11472. this._caps.drawBuffersExtension = true;
  11473. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11474. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11475. for (var i = 0; i < 16; i++) {
  11476. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11477. }
  11478. }
  11479. else {
  11480. this._caps.drawBuffersExtension = false;
  11481. }
  11482. }
  11483. // Depth Texture
  11484. if (this._webGLVersion > 1) {
  11485. this._caps.depthTextureExtension = true;
  11486. }
  11487. else {
  11488. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11489. if (depthTextureExtension != null) {
  11490. this._caps.depthTextureExtension = true;
  11491. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11492. }
  11493. }
  11494. // Vertex array object
  11495. if (this._webGLVersion > 1) {
  11496. this._caps.vertexArrayObject = true;
  11497. }
  11498. else {
  11499. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11500. if (vertexArrayObjectExtension != null) {
  11501. this._caps.vertexArrayObject = true;
  11502. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11503. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11504. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11505. }
  11506. else {
  11507. this._caps.vertexArrayObject = false;
  11508. }
  11509. }
  11510. // Instances count
  11511. if (this._webGLVersion > 1) {
  11512. this._caps.instancedArrays = true;
  11513. }
  11514. else {
  11515. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11516. if (instanceExtension != null) {
  11517. this._caps.instancedArrays = true;
  11518. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11519. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11520. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11521. }
  11522. else {
  11523. this._caps.instancedArrays = false;
  11524. }
  11525. }
  11526. // Intelligently add supported compressed formats in order to check for.
  11527. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11528. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11529. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11530. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11531. if (this._caps.astc)
  11532. this.texturesSupported.push('-astc.ktx');
  11533. if (this._caps.s3tc)
  11534. this.texturesSupported.push('-dxt.ktx');
  11535. if (this._caps.pvrtc)
  11536. this.texturesSupported.push('-pvrtc.ktx');
  11537. if (this._caps.etc2)
  11538. this.texturesSupported.push('-etc2.ktx');
  11539. if (this._caps.etc1)
  11540. this.texturesSupported.push('-etc1.ktx');
  11541. if (this._gl.getShaderPrecisionFormat) {
  11542. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11543. if (highp) {
  11544. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11545. }
  11546. }
  11547. // Depth buffer
  11548. this.setDepthBuffer(true);
  11549. this.setDepthFunctionToLessOrEqual();
  11550. this.setDepthWrite(true);
  11551. // Texture maps
  11552. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11553. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11554. this._nextFreeTextureSlots.push(slot);
  11555. }
  11556. };
  11557. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11558. get: function () {
  11559. return this._webGLVersion;
  11560. },
  11561. enumerable: true,
  11562. configurable: true
  11563. });
  11564. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11565. /**
  11566. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11567. */
  11568. get: function () {
  11569. return this._isStencilEnable;
  11570. },
  11571. enumerable: true,
  11572. configurable: true
  11573. });
  11574. Engine.prototype._prepareWorkingCanvas = function () {
  11575. if (this._workingCanvas) {
  11576. return;
  11577. }
  11578. this._workingCanvas = document.createElement("canvas");
  11579. var context = this._workingCanvas.getContext("2d");
  11580. if (context) {
  11581. this._workingContext = context;
  11582. }
  11583. };
  11584. Engine.prototype.resetTextureCache = function () {
  11585. for (var key in this._boundTexturesCache) {
  11586. var boundTexture = this._boundTexturesCache[key];
  11587. if (boundTexture) {
  11588. this._removeDesignatedSlot(boundTexture);
  11589. }
  11590. this._boundTexturesCache[key] = null;
  11591. }
  11592. if (!this.disableTextureBindingOptimization) {
  11593. this._nextFreeTextureSlots = [];
  11594. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11595. this._nextFreeTextureSlots.push(slot);
  11596. }
  11597. }
  11598. this._currentTextureChannel = -1;
  11599. };
  11600. Engine.prototype.isDeterministicLockStep = function () {
  11601. return this._deterministicLockstep;
  11602. };
  11603. Engine.prototype.getLockstepMaxSteps = function () {
  11604. return this._lockstepMaxSteps;
  11605. };
  11606. Engine.prototype.getGlInfo = function () {
  11607. return {
  11608. vendor: this._glVendor,
  11609. renderer: this._glRenderer,
  11610. version: this._glVersion
  11611. };
  11612. };
  11613. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11614. if (useScreen === void 0) { useScreen = false; }
  11615. var viewport = camera.viewport;
  11616. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11617. };
  11618. Engine.prototype.getRenderWidth = function (useScreen) {
  11619. if (useScreen === void 0) { useScreen = false; }
  11620. if (!useScreen && this._currentRenderTarget) {
  11621. return this._currentRenderTarget.width;
  11622. }
  11623. return this._gl.drawingBufferWidth;
  11624. };
  11625. Engine.prototype.getRenderHeight = function (useScreen) {
  11626. if (useScreen === void 0) { useScreen = false; }
  11627. if (!useScreen && this._currentRenderTarget) {
  11628. return this._currentRenderTarget.height;
  11629. }
  11630. return this._gl.drawingBufferHeight;
  11631. };
  11632. Engine.prototype.getRenderingCanvas = function () {
  11633. return this._renderingCanvas;
  11634. };
  11635. Engine.prototype.getRenderingCanvasClientRect = function () {
  11636. if (!this._renderingCanvas) {
  11637. return null;
  11638. }
  11639. return this._renderingCanvas.getBoundingClientRect();
  11640. };
  11641. Engine.prototype.setHardwareScalingLevel = function (level) {
  11642. this._hardwareScalingLevel = level;
  11643. this.resize();
  11644. };
  11645. Engine.prototype.getHardwareScalingLevel = function () {
  11646. return this._hardwareScalingLevel;
  11647. };
  11648. Engine.prototype.getLoadedTexturesCache = function () {
  11649. return this._internalTexturesCache;
  11650. };
  11651. Engine.prototype.getCaps = function () {
  11652. return this._caps;
  11653. };
  11654. Object.defineProperty(Engine.prototype, "drawCalls", {
  11655. /** The number of draw calls submitted last frame */
  11656. get: function () {
  11657. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11658. return 0;
  11659. },
  11660. enumerable: true,
  11661. configurable: true
  11662. });
  11663. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11664. get: function () {
  11665. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11666. return null;
  11667. },
  11668. enumerable: true,
  11669. configurable: true
  11670. });
  11671. Engine.prototype.getDepthFunction = function () {
  11672. return this._depthCullingState.depthFunc;
  11673. };
  11674. Engine.prototype.setDepthFunction = function (depthFunc) {
  11675. this._depthCullingState.depthFunc = depthFunc;
  11676. };
  11677. Engine.prototype.setDepthFunctionToGreater = function () {
  11678. this._depthCullingState.depthFunc = this._gl.GREATER;
  11679. };
  11680. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11681. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11682. };
  11683. Engine.prototype.setDepthFunctionToLess = function () {
  11684. this._depthCullingState.depthFunc = this._gl.LESS;
  11685. };
  11686. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11687. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11688. };
  11689. Engine.prototype.getStencilBuffer = function () {
  11690. return this._stencilState.stencilTest;
  11691. };
  11692. Engine.prototype.setStencilBuffer = function (enable) {
  11693. this._stencilState.stencilTest = enable;
  11694. };
  11695. Engine.prototype.getStencilMask = function () {
  11696. return this._stencilState.stencilMask;
  11697. };
  11698. Engine.prototype.setStencilMask = function (mask) {
  11699. this._stencilState.stencilMask = mask;
  11700. };
  11701. Engine.prototype.getStencilFunction = function () {
  11702. return this._stencilState.stencilFunc;
  11703. };
  11704. Engine.prototype.getStencilFunctionReference = function () {
  11705. return this._stencilState.stencilFuncRef;
  11706. };
  11707. Engine.prototype.getStencilFunctionMask = function () {
  11708. return this._stencilState.stencilFuncMask;
  11709. };
  11710. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11711. this._stencilState.stencilFunc = stencilFunc;
  11712. };
  11713. Engine.prototype.setStencilFunctionReference = function (reference) {
  11714. this._stencilState.stencilFuncRef = reference;
  11715. };
  11716. Engine.prototype.setStencilFunctionMask = function (mask) {
  11717. this._stencilState.stencilFuncMask = mask;
  11718. };
  11719. Engine.prototype.getStencilOperationFail = function () {
  11720. return this._stencilState.stencilOpStencilFail;
  11721. };
  11722. Engine.prototype.getStencilOperationDepthFail = function () {
  11723. return this._stencilState.stencilOpDepthFail;
  11724. };
  11725. Engine.prototype.getStencilOperationPass = function () {
  11726. return this._stencilState.stencilOpStencilDepthPass;
  11727. };
  11728. Engine.prototype.setStencilOperationFail = function (operation) {
  11729. this._stencilState.stencilOpStencilFail = operation;
  11730. };
  11731. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11732. this._stencilState.stencilOpDepthFail = operation;
  11733. };
  11734. Engine.prototype.setStencilOperationPass = function (operation) {
  11735. this._stencilState.stencilOpStencilDepthPass = operation;
  11736. };
  11737. Engine.prototype.setDitheringState = function (value) {
  11738. if (value) {
  11739. this._gl.enable(this._gl.DITHER);
  11740. }
  11741. else {
  11742. this._gl.disable(this._gl.DITHER);
  11743. }
  11744. };
  11745. Engine.prototype.setRasterizerState = function (value) {
  11746. if (value) {
  11747. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11748. }
  11749. else {
  11750. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11751. }
  11752. };
  11753. /**
  11754. * stop executing a render loop function and remove it from the execution array
  11755. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11756. */
  11757. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11758. if (!renderFunction) {
  11759. this._activeRenderLoops = [];
  11760. return;
  11761. }
  11762. var index = this._activeRenderLoops.indexOf(renderFunction);
  11763. if (index >= 0) {
  11764. this._activeRenderLoops.splice(index, 1);
  11765. }
  11766. };
  11767. Engine.prototype._renderLoop = function () {
  11768. if (!this._contextWasLost) {
  11769. var shouldRender = true;
  11770. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11771. shouldRender = false;
  11772. }
  11773. if (shouldRender) {
  11774. // Start new frame
  11775. this.beginFrame();
  11776. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11777. var renderFunction = this._activeRenderLoops[index];
  11778. renderFunction();
  11779. }
  11780. // Present
  11781. this.endFrame();
  11782. }
  11783. }
  11784. if (this._activeRenderLoops.length > 0) {
  11785. // Register new frame
  11786. var requester = null;
  11787. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11788. requester = this._vrDisplay;
  11789. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11790. }
  11791. else {
  11792. this._renderingQueueLaunched = false;
  11793. }
  11794. };
  11795. /**
  11796. * Register and execute a render loop. The engine can have more than one render function.
  11797. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11798. * @example
  11799. * engine.runRenderLoop(function () {
  11800. * scene.render()
  11801. * })
  11802. */
  11803. Engine.prototype.runRenderLoop = function (renderFunction) {
  11804. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11805. return;
  11806. }
  11807. this._activeRenderLoops.push(renderFunction);
  11808. if (!this._renderingQueueLaunched) {
  11809. this._renderingQueueLaunched = true;
  11810. this._bindedRenderFunction = this._renderLoop.bind(this);
  11811. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11812. }
  11813. };
  11814. /**
  11815. * Toggle full screen mode.
  11816. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11817. * @param {any} options - an options object to be sent to the requestFullscreen function
  11818. */
  11819. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11820. if (this.isFullscreen) {
  11821. BABYLON.Tools.ExitFullscreen();
  11822. }
  11823. else {
  11824. this._pointerLockRequested = requestPointerLock;
  11825. if (this._renderingCanvas) {
  11826. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11827. }
  11828. }
  11829. };
  11830. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11831. if (stencil === void 0) { stencil = false; }
  11832. this.applyStates();
  11833. var mode = 0;
  11834. if (backBuffer && color) {
  11835. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11836. mode |= this._gl.COLOR_BUFFER_BIT;
  11837. }
  11838. if (depth) {
  11839. this._gl.clearDepth(1.0);
  11840. mode |= this._gl.DEPTH_BUFFER_BIT;
  11841. }
  11842. if (stencil) {
  11843. this._gl.clearStencil(0);
  11844. mode |= this._gl.STENCIL_BUFFER_BIT;
  11845. }
  11846. this._gl.clear(mode);
  11847. };
  11848. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11849. var gl = this._gl;
  11850. // Save state
  11851. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11852. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11853. // Change state
  11854. gl.enable(gl.SCISSOR_TEST);
  11855. gl.scissor(x, y, width, height);
  11856. // Clear
  11857. this.clear(clearColor, true, true, true);
  11858. // Restore state
  11859. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11860. if (curScissor === true) {
  11861. gl.enable(gl.SCISSOR_TEST);
  11862. }
  11863. else {
  11864. gl.disable(gl.SCISSOR_TEST);
  11865. }
  11866. };
  11867. /**
  11868. * Set the WebGL's viewport
  11869. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11870. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11871. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11872. */
  11873. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11874. var width = requiredWidth || this.getRenderWidth();
  11875. var height = requiredHeight || this.getRenderHeight();
  11876. var x = viewport.x || 0;
  11877. var y = viewport.y || 0;
  11878. this._cachedViewport = viewport;
  11879. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11880. };
  11881. /**
  11882. * Directly set the WebGL Viewport
  11883. * The x, y, width & height are directly passed to the WebGL call
  11884. * @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.
  11885. */
  11886. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11887. var currentViewport = this._cachedViewport;
  11888. this._cachedViewport = null;
  11889. this._gl.viewport(x, y, width, height);
  11890. return currentViewport;
  11891. };
  11892. Engine.prototype.beginFrame = function () {
  11893. this.onBeginFrameObservable.notifyObservers(this);
  11894. this._measureFps();
  11895. };
  11896. Engine.prototype.endFrame = function () {
  11897. //force a flush in case we are using a bad OS.
  11898. if (this._badOS) {
  11899. this.flushFramebuffer();
  11900. }
  11901. //submit frame to the vr device, if enabled
  11902. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11903. // TODO: We should only submit the frame if we read frameData successfully.
  11904. this._vrDisplay.submitFrame();
  11905. }
  11906. this.onEndFrameObservable.notifyObservers(this);
  11907. };
  11908. /**
  11909. * resize the view according to the canvas' size.
  11910. * @example
  11911. * window.addEventListener("resize", function () {
  11912. * engine.resize();
  11913. * });
  11914. */
  11915. Engine.prototype.resize = function () {
  11916. // We're not resizing the size of the canvas while in VR mode & presenting
  11917. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11918. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11919. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11920. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11921. }
  11922. };
  11923. /**
  11924. * force a specific size of the canvas
  11925. * @param {number} width - the new canvas' width
  11926. * @param {number} height - the new canvas' height
  11927. */
  11928. Engine.prototype.setSize = function (width, height) {
  11929. if (!this._renderingCanvas) {
  11930. return;
  11931. }
  11932. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11933. return;
  11934. }
  11935. this._renderingCanvas.width = width;
  11936. this._renderingCanvas.height = height;
  11937. for (var index = 0; index < this.scenes.length; index++) {
  11938. var scene = this.scenes[index];
  11939. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11940. var cam = scene.cameras[camIndex];
  11941. cam._currentRenderId = 0;
  11942. }
  11943. }
  11944. if (this.onResizeObservable.hasObservers) {
  11945. this.onResizeObservable.notifyObservers(this);
  11946. }
  11947. };
  11948. // WebVR functions
  11949. Engine.prototype.isVRDevicePresent = function () {
  11950. return !!this._vrDisplay;
  11951. };
  11952. Engine.prototype.getVRDevice = function () {
  11953. return this._vrDisplay;
  11954. };
  11955. /**
  11956. * Initializes a webVR display and starts listening to display change events.
  11957. * The onVRDisplayChangedObservable will be notified upon these changes.
  11958. * @returns The onVRDisplayChangedObservable.
  11959. */
  11960. Engine.prototype.initWebVR = function () {
  11961. this.initWebVRAsync();
  11962. return this.onVRDisplayChangedObservable;
  11963. };
  11964. /**
  11965. * Initializes a webVR display and starts listening to display change events.
  11966. * The onVRDisplayChangedObservable will be notified upon these changes.
  11967. * @returns A promise containing a VRDisplay and if vr is supported.
  11968. */
  11969. Engine.prototype.initWebVRAsync = function () {
  11970. var _this = this;
  11971. var notifyObservers = function () {
  11972. var eventArgs = {
  11973. vrDisplay: _this._vrDisplay,
  11974. vrSupported: _this._vrSupported
  11975. };
  11976. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11977. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11978. };
  11979. if (!this._onVrDisplayConnect) {
  11980. this._onVrDisplayConnect = function (event) {
  11981. _this._vrDisplay = event.display;
  11982. notifyObservers();
  11983. };
  11984. this._onVrDisplayDisconnect = function () {
  11985. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11986. _this._vrDisplay = undefined;
  11987. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11988. notifyObservers();
  11989. };
  11990. this._onVrDisplayPresentChange = function () {
  11991. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11992. };
  11993. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11994. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11995. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11996. }
  11997. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11998. this._webVRInitPromise.then(notifyObservers);
  11999. return this._webVRInitPromise;
  12000. };
  12001. Engine.prototype.enableVR = function () {
  12002. var _this = this;
  12003. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12004. var onResolved = function () {
  12005. _this.onVRRequestPresentComplete.notifyObservers(true);
  12006. _this._onVRFullScreenTriggered();
  12007. };
  12008. var onRejected = function () {
  12009. _this.onVRRequestPresentComplete.notifyObservers(false);
  12010. };
  12011. this.onVRRequestPresentStart.notifyObservers(this);
  12012. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12013. }
  12014. };
  12015. Engine.prototype.disableVR = function () {
  12016. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12017. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12018. }
  12019. };
  12020. Engine.prototype._getVRDisplaysAsync = function () {
  12021. var _this = this;
  12022. return new Promise(function (res, rej) {
  12023. if (navigator.getVRDisplays) {
  12024. navigator.getVRDisplays().then(function (devices) {
  12025. _this._vrSupported = true;
  12026. // note that devices may actually be an empty array. This is fine;
  12027. // we expect this._vrDisplay to be undefined in this case.
  12028. _this._vrDisplay = devices[0];
  12029. res({
  12030. vrDisplay: _this._vrDisplay,
  12031. vrSupported: _this._vrSupported
  12032. });
  12033. });
  12034. }
  12035. else {
  12036. _this._vrDisplay = undefined;
  12037. _this._vrSupported = false;
  12038. res({
  12039. vrDisplay: _this._vrDisplay,
  12040. vrSupported: _this._vrSupported
  12041. });
  12042. }
  12043. });
  12044. };
  12045. /**
  12046. * Binds the frame buffer to the specified texture.
  12047. * @param texture The texture to render to or null for the default canvas
  12048. * @param faceIndex The face of the texture to render to in case of cube texture
  12049. * @param requiredWidth The width of the target to render to
  12050. * @param requiredHeight The height of the target to render to
  12051. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12052. * @param depthStencilTexture The depth stencil texture to use to render
  12053. */
  12054. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12055. if (this._currentRenderTarget) {
  12056. this.unBindFramebuffer(this._currentRenderTarget);
  12057. }
  12058. this._currentRenderTarget = texture;
  12059. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12060. var gl = this._gl;
  12061. if (texture.isCube) {
  12062. if (faceIndex === undefined) {
  12063. faceIndex = 0;
  12064. }
  12065. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12066. if (depthStencilTexture) {
  12067. if (depthStencilTexture._generateStencilBuffer) {
  12068. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12069. }
  12070. else {
  12071. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12072. }
  12073. }
  12074. }
  12075. if (this._cachedViewport && !forceFullscreenViewport) {
  12076. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12077. }
  12078. else {
  12079. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12080. }
  12081. this.wipeCaches();
  12082. };
  12083. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12084. if (this._currentFramebuffer !== framebuffer) {
  12085. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12086. this._currentFramebuffer = framebuffer;
  12087. }
  12088. };
  12089. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12090. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12091. this._currentRenderTarget = null;
  12092. // If MSAA, we need to bitblt back to main texture
  12093. var gl = this._gl;
  12094. if (texture._MSAAFramebuffer) {
  12095. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12096. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12097. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12098. }
  12099. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12100. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12101. gl.generateMipmap(gl.TEXTURE_2D);
  12102. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12103. }
  12104. if (onBeforeUnbind) {
  12105. if (texture._MSAAFramebuffer) {
  12106. // Bind the correct framebuffer
  12107. this.bindUnboundFramebuffer(texture._framebuffer);
  12108. }
  12109. onBeforeUnbind();
  12110. }
  12111. this.bindUnboundFramebuffer(null);
  12112. };
  12113. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12114. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12115. this._currentRenderTarget = null;
  12116. // If MSAA, we need to bitblt back to main texture
  12117. var gl = this._gl;
  12118. if (textures[0]._MSAAFramebuffer) {
  12119. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12120. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12121. var attachments = textures[0]._attachments;
  12122. if (!attachments) {
  12123. attachments = new Array(textures.length);
  12124. textures[0]._attachments = attachments;
  12125. }
  12126. for (var i = 0; i < textures.length; i++) {
  12127. var texture = textures[i];
  12128. for (var j = 0; j < attachments.length; j++) {
  12129. attachments[j] = gl.NONE;
  12130. }
  12131. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12132. gl.readBuffer(attachments[i]);
  12133. gl.drawBuffers(attachments);
  12134. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12135. }
  12136. for (var i = 0; i < attachments.length; i++) {
  12137. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12138. }
  12139. gl.drawBuffers(attachments);
  12140. }
  12141. for (var i = 0; i < textures.length; i++) {
  12142. var texture = textures[i];
  12143. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12144. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12145. gl.generateMipmap(gl.TEXTURE_2D);
  12146. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12147. }
  12148. }
  12149. if (onBeforeUnbind) {
  12150. if (textures[0]._MSAAFramebuffer) {
  12151. // Bind the correct framebuffer
  12152. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12153. }
  12154. onBeforeUnbind();
  12155. }
  12156. this.bindUnboundFramebuffer(null);
  12157. };
  12158. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12159. if (texture.generateMipMaps) {
  12160. var gl = this._gl;
  12161. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12162. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12163. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12164. }
  12165. };
  12166. Engine.prototype.flushFramebuffer = function () {
  12167. this._gl.flush();
  12168. };
  12169. Engine.prototype.restoreDefaultFramebuffer = function () {
  12170. if (this._currentRenderTarget) {
  12171. this.unBindFramebuffer(this._currentRenderTarget);
  12172. }
  12173. else {
  12174. this.bindUnboundFramebuffer(null);
  12175. }
  12176. if (this._cachedViewport) {
  12177. this.setViewport(this._cachedViewport);
  12178. }
  12179. this.wipeCaches();
  12180. };
  12181. // UBOs
  12182. Engine.prototype.createUniformBuffer = function (elements) {
  12183. var ubo = this._gl.createBuffer();
  12184. if (!ubo) {
  12185. throw new Error("Unable to create uniform buffer");
  12186. }
  12187. this.bindUniformBuffer(ubo);
  12188. if (elements instanceof Float32Array) {
  12189. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12190. }
  12191. else {
  12192. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12193. }
  12194. this.bindUniformBuffer(null);
  12195. ubo.references = 1;
  12196. return ubo;
  12197. };
  12198. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12199. var ubo = this._gl.createBuffer();
  12200. if (!ubo) {
  12201. throw new Error("Unable to create dynamic uniform buffer");
  12202. }
  12203. this.bindUniformBuffer(ubo);
  12204. if (elements instanceof Float32Array) {
  12205. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12206. }
  12207. else {
  12208. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12209. }
  12210. this.bindUniformBuffer(null);
  12211. ubo.references = 1;
  12212. return ubo;
  12213. };
  12214. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12215. this.bindUniformBuffer(uniformBuffer);
  12216. if (offset === undefined) {
  12217. offset = 0;
  12218. }
  12219. if (count === undefined) {
  12220. if (elements instanceof Float32Array) {
  12221. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12222. }
  12223. else {
  12224. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12225. }
  12226. }
  12227. else {
  12228. if (elements instanceof Float32Array) {
  12229. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12230. }
  12231. else {
  12232. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12233. }
  12234. }
  12235. this.bindUniformBuffer(null);
  12236. };
  12237. // VBOs
  12238. Engine.prototype._resetVertexBufferBinding = function () {
  12239. this.bindArrayBuffer(null);
  12240. this._cachedVertexBuffers = null;
  12241. };
  12242. Engine.prototype.createVertexBuffer = function (vertices) {
  12243. var vbo = this._gl.createBuffer();
  12244. if (!vbo) {
  12245. throw new Error("Unable to create vertex buffer");
  12246. }
  12247. this.bindArrayBuffer(vbo);
  12248. if (vertices instanceof Float32Array) {
  12249. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12250. }
  12251. else {
  12252. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12253. }
  12254. this._resetVertexBufferBinding();
  12255. vbo.references = 1;
  12256. return vbo;
  12257. };
  12258. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12259. var vbo = this._gl.createBuffer();
  12260. if (!vbo) {
  12261. throw new Error("Unable to create dynamic vertex buffer");
  12262. }
  12263. this.bindArrayBuffer(vbo);
  12264. if (vertices instanceof Float32Array) {
  12265. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12266. }
  12267. else {
  12268. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12269. }
  12270. this._resetVertexBufferBinding();
  12271. vbo.references = 1;
  12272. return vbo;
  12273. };
  12274. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12275. if (offset === void 0) { offset = 0; }
  12276. // Force cache update
  12277. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12278. this.bindIndexBuffer(indexBuffer);
  12279. var arrayBuffer;
  12280. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12281. arrayBuffer = indices;
  12282. }
  12283. else {
  12284. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12285. }
  12286. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12287. this._resetIndexBufferBinding();
  12288. };
  12289. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12290. this.bindArrayBuffer(vertexBuffer);
  12291. if (offset === undefined) {
  12292. offset = 0;
  12293. }
  12294. if (count === undefined) {
  12295. if (vertices instanceof Float32Array) {
  12296. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12297. }
  12298. else {
  12299. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12300. }
  12301. }
  12302. else {
  12303. if (vertices instanceof Float32Array) {
  12304. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12305. }
  12306. else {
  12307. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12308. }
  12309. }
  12310. this._resetVertexBufferBinding();
  12311. };
  12312. Engine.prototype._resetIndexBufferBinding = function () {
  12313. this.bindIndexBuffer(null);
  12314. this._cachedIndexBuffer = null;
  12315. };
  12316. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12317. var vbo = this._gl.createBuffer();
  12318. if (!vbo) {
  12319. throw new Error("Unable to create index buffer");
  12320. }
  12321. this.bindIndexBuffer(vbo);
  12322. // Check for 32 bits indices
  12323. var arrayBuffer;
  12324. var need32Bits = false;
  12325. if (indices instanceof Uint16Array) {
  12326. arrayBuffer = indices;
  12327. }
  12328. else {
  12329. //check 32 bit support
  12330. if (this._caps.uintIndices) {
  12331. if (indices instanceof Uint32Array) {
  12332. arrayBuffer = indices;
  12333. need32Bits = true;
  12334. }
  12335. else {
  12336. //number[] or Int32Array, check if 32 bit is necessary
  12337. for (var index = 0; index < indices.length; index++) {
  12338. if (indices[index] > 65535) {
  12339. need32Bits = true;
  12340. break;
  12341. }
  12342. }
  12343. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12344. }
  12345. }
  12346. else {
  12347. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12348. arrayBuffer = new Uint16Array(indices);
  12349. }
  12350. }
  12351. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12352. this._resetIndexBufferBinding();
  12353. vbo.references = 1;
  12354. vbo.is32Bits = need32Bits;
  12355. return vbo;
  12356. };
  12357. Engine.prototype.bindArrayBuffer = function (buffer) {
  12358. if (!this._vaoRecordInProgress) {
  12359. this._unbindVertexArrayObject();
  12360. }
  12361. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12362. };
  12363. Engine.prototype.bindUniformBuffer = function (buffer) {
  12364. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12365. };
  12366. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12367. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12368. };
  12369. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12370. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12371. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12372. };
  12373. ;
  12374. Engine.prototype.bindIndexBuffer = function (buffer) {
  12375. if (!this._vaoRecordInProgress) {
  12376. this._unbindVertexArrayObject();
  12377. }
  12378. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12379. };
  12380. Engine.prototype.bindBuffer = function (buffer, target) {
  12381. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12382. this._gl.bindBuffer(target, buffer);
  12383. this._currentBoundBuffer[target] = buffer;
  12384. }
  12385. };
  12386. Engine.prototype.updateArrayBuffer = function (data) {
  12387. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12388. };
  12389. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12390. var pointer = this._currentBufferPointers[indx];
  12391. var changed = false;
  12392. if (!pointer.active) {
  12393. changed = true;
  12394. pointer.active = true;
  12395. pointer.index = indx;
  12396. pointer.size = size;
  12397. pointer.type = type;
  12398. pointer.normalized = normalized;
  12399. pointer.stride = stride;
  12400. pointer.offset = offset;
  12401. pointer.buffer = buffer;
  12402. }
  12403. else {
  12404. if (pointer.buffer !== buffer) {
  12405. pointer.buffer = buffer;
  12406. changed = true;
  12407. }
  12408. if (pointer.size !== size) {
  12409. pointer.size = size;
  12410. changed = true;
  12411. }
  12412. if (pointer.type !== type) {
  12413. pointer.type = type;
  12414. changed = true;
  12415. }
  12416. if (pointer.normalized !== normalized) {
  12417. pointer.normalized = normalized;
  12418. changed = true;
  12419. }
  12420. if (pointer.stride !== stride) {
  12421. pointer.stride = stride;
  12422. changed = true;
  12423. }
  12424. if (pointer.offset !== offset) {
  12425. pointer.offset = offset;
  12426. changed = true;
  12427. }
  12428. }
  12429. if (changed || this._vaoRecordInProgress) {
  12430. this.bindArrayBuffer(buffer);
  12431. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12432. }
  12433. };
  12434. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12435. if (indexBuffer == null) {
  12436. return;
  12437. }
  12438. if (this._cachedIndexBuffer !== indexBuffer) {
  12439. this._cachedIndexBuffer = indexBuffer;
  12440. this.bindIndexBuffer(indexBuffer);
  12441. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12442. }
  12443. };
  12444. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12445. var attributes = effect.getAttributesNames();
  12446. if (!this._vaoRecordInProgress) {
  12447. this._unbindVertexArrayObject();
  12448. }
  12449. this.unbindAllAttributes();
  12450. for (var index = 0; index < attributes.length; index++) {
  12451. var order = effect.getAttributeLocation(index);
  12452. if (order >= 0) {
  12453. var vertexBuffer = vertexBuffers[attributes[index]];
  12454. if (!vertexBuffer) {
  12455. continue;
  12456. }
  12457. this._gl.enableVertexAttribArray(order);
  12458. if (!this._vaoRecordInProgress) {
  12459. this._vertexAttribArraysEnabled[order] = true;
  12460. }
  12461. var buffer = vertexBuffer.getBuffer();
  12462. if (buffer) {
  12463. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12464. if (vertexBuffer.getIsInstanced()) {
  12465. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12466. if (!this._vaoRecordInProgress) {
  12467. this._currentInstanceLocations.push(order);
  12468. this._currentInstanceBuffers.push(buffer);
  12469. }
  12470. }
  12471. }
  12472. }
  12473. }
  12474. };
  12475. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12476. var vao = this._gl.createVertexArray();
  12477. this._vaoRecordInProgress = true;
  12478. this._gl.bindVertexArray(vao);
  12479. this._mustWipeVertexAttributes = true;
  12480. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12481. this.bindIndexBuffer(indexBuffer);
  12482. this._vaoRecordInProgress = false;
  12483. this._gl.bindVertexArray(null);
  12484. return vao;
  12485. };
  12486. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12487. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12488. this._cachedVertexArrayObject = vertexArrayObject;
  12489. this._gl.bindVertexArray(vertexArrayObject);
  12490. this._cachedVertexBuffers = null;
  12491. this._cachedIndexBuffer = null;
  12492. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12493. this._mustWipeVertexAttributes = true;
  12494. }
  12495. };
  12496. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12497. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12498. this._cachedVertexBuffers = vertexBuffer;
  12499. this._cachedEffectForVertexBuffers = effect;
  12500. var attributesCount = effect.getAttributesCount();
  12501. this._unbindVertexArrayObject();
  12502. this.unbindAllAttributes();
  12503. var offset = 0;
  12504. for (var index = 0; index < attributesCount; index++) {
  12505. if (index < vertexDeclaration.length) {
  12506. var order = effect.getAttributeLocation(index);
  12507. if (order >= 0) {
  12508. this._gl.enableVertexAttribArray(order);
  12509. this._vertexAttribArraysEnabled[order] = true;
  12510. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12511. }
  12512. offset += vertexDeclaration[index] * 4;
  12513. }
  12514. }
  12515. }
  12516. this._bindIndexBufferWithCache(indexBuffer);
  12517. };
  12518. Engine.prototype._unbindVertexArrayObject = function () {
  12519. if (!this._cachedVertexArrayObject) {
  12520. return;
  12521. }
  12522. this._cachedVertexArrayObject = null;
  12523. this._gl.bindVertexArray(null);
  12524. };
  12525. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12526. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12527. this._cachedVertexBuffers = vertexBuffers;
  12528. this._cachedEffectForVertexBuffers = effect;
  12529. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12530. }
  12531. this._bindIndexBufferWithCache(indexBuffer);
  12532. };
  12533. Engine.prototype.unbindInstanceAttributes = function () {
  12534. var boundBuffer;
  12535. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12536. var instancesBuffer = this._currentInstanceBuffers[i];
  12537. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12538. boundBuffer = instancesBuffer;
  12539. this.bindArrayBuffer(instancesBuffer);
  12540. }
  12541. var offsetLocation = this._currentInstanceLocations[i];
  12542. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12543. }
  12544. this._currentInstanceBuffers.length = 0;
  12545. this._currentInstanceLocations.length = 0;
  12546. };
  12547. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12548. this._gl.deleteVertexArray(vao);
  12549. };
  12550. Engine.prototype._releaseBuffer = function (buffer) {
  12551. buffer.references--;
  12552. if (buffer.references === 0) {
  12553. this._gl.deleteBuffer(buffer);
  12554. return true;
  12555. }
  12556. return false;
  12557. };
  12558. Engine.prototype.createInstancesBuffer = function (capacity) {
  12559. var buffer = this._gl.createBuffer();
  12560. if (!buffer) {
  12561. throw new Error("Unable to create instance buffer");
  12562. }
  12563. buffer.capacity = capacity;
  12564. this.bindArrayBuffer(buffer);
  12565. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12566. return buffer;
  12567. };
  12568. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12569. this._gl.deleteBuffer(buffer);
  12570. };
  12571. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12572. this.bindArrayBuffer(instancesBuffer);
  12573. if (data) {
  12574. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12575. }
  12576. if (offsetLocations[0].index !== undefined) {
  12577. var stride = 0;
  12578. for (var i = 0; i < offsetLocations.length; i++) {
  12579. var ai = offsetLocations[i];
  12580. stride += ai.attributeSize * 4;
  12581. }
  12582. for (var i = 0; i < offsetLocations.length; i++) {
  12583. var ai = offsetLocations[i];
  12584. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12585. this._gl.enableVertexAttribArray(ai.index);
  12586. this._vertexAttribArraysEnabled[ai.index] = true;
  12587. }
  12588. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12589. this._gl.vertexAttribDivisor(ai.index, 1);
  12590. this._currentInstanceLocations.push(ai.index);
  12591. this._currentInstanceBuffers.push(instancesBuffer);
  12592. }
  12593. }
  12594. else {
  12595. for (var index = 0; index < 4; index++) {
  12596. var offsetLocation = offsetLocations[index];
  12597. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12598. this._gl.enableVertexAttribArray(offsetLocation);
  12599. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12600. }
  12601. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12602. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12603. this._currentInstanceLocations.push(offsetLocation);
  12604. this._currentInstanceBuffers.push(instancesBuffer);
  12605. }
  12606. }
  12607. };
  12608. Engine.prototype.applyStates = function () {
  12609. this._depthCullingState.apply(this._gl);
  12610. this._stencilState.apply(this._gl);
  12611. this._alphaState.apply(this._gl);
  12612. };
  12613. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12614. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12615. };
  12616. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12617. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12618. };
  12619. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12620. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12621. };
  12622. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12623. // Apply states
  12624. this.applyStates();
  12625. this._drawCalls.addCount(1, false);
  12626. // Render
  12627. var drawMode = this._drawMode(fillMode);
  12628. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12629. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12630. if (instancesCount) {
  12631. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12632. }
  12633. else {
  12634. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12635. }
  12636. };
  12637. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12638. // Apply states
  12639. this.applyStates();
  12640. this._drawCalls.addCount(1, false);
  12641. var drawMode = this._drawMode(fillMode);
  12642. if (instancesCount) {
  12643. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12644. }
  12645. else {
  12646. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12647. }
  12648. };
  12649. Engine.prototype._drawMode = function (fillMode) {
  12650. switch (fillMode) {
  12651. // Triangle views
  12652. case BABYLON.Material.TriangleFillMode:
  12653. return this._gl.TRIANGLES;
  12654. case BABYLON.Material.PointFillMode:
  12655. return this._gl.POINTS;
  12656. case BABYLON.Material.WireFrameFillMode:
  12657. return this._gl.LINES;
  12658. // Draw modes
  12659. case BABYLON.Material.PointListDrawMode:
  12660. return this._gl.POINTS;
  12661. case BABYLON.Material.LineListDrawMode:
  12662. return this._gl.LINES;
  12663. case BABYLON.Material.LineLoopDrawMode:
  12664. return this._gl.LINE_LOOP;
  12665. case BABYLON.Material.LineStripDrawMode:
  12666. return this._gl.LINE_STRIP;
  12667. case BABYLON.Material.TriangleStripDrawMode:
  12668. return this._gl.TRIANGLE_STRIP;
  12669. case BABYLON.Material.TriangleFanDrawMode:
  12670. return this._gl.TRIANGLE_FAN;
  12671. default:
  12672. return this._gl.TRIANGLES;
  12673. }
  12674. };
  12675. // Shaders
  12676. Engine.prototype._releaseEffect = function (effect) {
  12677. if (this._compiledEffects[effect._key]) {
  12678. delete this._compiledEffects[effect._key];
  12679. this._deleteProgram(effect.getProgram());
  12680. }
  12681. };
  12682. Engine.prototype._deleteProgram = function (program) {
  12683. if (program) {
  12684. program.__SPECTOR_rebuildProgram = null;
  12685. if (program.transformFeedback) {
  12686. this.deleteTransformFeedback(program.transformFeedback);
  12687. program.transformFeedback = null;
  12688. }
  12689. this._gl.deleteProgram(program);
  12690. }
  12691. };
  12692. /**
  12693. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12694. * @param samplers An array of string used to represent textures
  12695. */
  12696. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12697. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12698. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12699. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12700. if (this._compiledEffects[name]) {
  12701. var compiledEffect = this._compiledEffects[name];
  12702. if (onCompiled && compiledEffect.isReady()) {
  12703. onCompiled(compiledEffect);
  12704. }
  12705. return compiledEffect;
  12706. }
  12707. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12708. effect._key = name;
  12709. this._compiledEffects[name] = effect;
  12710. return effect;
  12711. };
  12712. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12713. if (uniformsNames === void 0) { uniformsNames = []; }
  12714. if (samplers === void 0) { samplers = []; }
  12715. if (defines === void 0) { defines = ""; }
  12716. return this.createEffect({
  12717. vertex: "particles",
  12718. fragmentElement: fragmentName
  12719. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12720. };
  12721. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12722. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12723. context = context || this._gl;
  12724. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12725. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12726. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12727. };
  12728. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12729. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12730. context = context || this._gl;
  12731. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12732. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  12733. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12734. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12735. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12736. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12737. return program;
  12738. };
  12739. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12740. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12741. var shaderProgram = context.createProgram();
  12742. if (!shaderProgram) {
  12743. throw new Error("Unable to create program");
  12744. }
  12745. context.attachShader(shaderProgram, vertexShader);
  12746. context.attachShader(shaderProgram, fragmentShader);
  12747. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12748. var transformFeedback = this.createTransformFeedback();
  12749. this.bindTransformFeedback(transformFeedback);
  12750. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12751. shaderProgram.transformFeedback = transformFeedback;
  12752. }
  12753. context.linkProgram(shaderProgram);
  12754. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12755. this.bindTransformFeedback(null);
  12756. }
  12757. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12758. if (!linked) {
  12759. context.validateProgram(shaderProgram);
  12760. var error = context.getProgramInfoLog(shaderProgram);
  12761. if (error) {
  12762. throw new Error(error);
  12763. }
  12764. }
  12765. context.deleteShader(vertexShader);
  12766. context.deleteShader(fragmentShader);
  12767. return shaderProgram;
  12768. };
  12769. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12770. var results = new Array();
  12771. for (var index = 0; index < uniformsNames.length; index++) {
  12772. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12773. }
  12774. return results;
  12775. };
  12776. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12777. var results = [];
  12778. for (var index = 0; index < attributesNames.length; index++) {
  12779. try {
  12780. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12781. }
  12782. catch (e) {
  12783. results.push(-1);
  12784. }
  12785. }
  12786. return results;
  12787. };
  12788. Engine.prototype.enableEffect = function (effect) {
  12789. if (!effect) {
  12790. return;
  12791. }
  12792. // Use program
  12793. this.bindSamplers(effect);
  12794. this._currentEffect = effect;
  12795. if (effect.onBind) {
  12796. effect.onBind(effect);
  12797. }
  12798. effect.onBindObservable.notifyObservers(effect);
  12799. };
  12800. Engine.prototype.setIntArray = function (uniform, array) {
  12801. if (!uniform)
  12802. return;
  12803. this._gl.uniform1iv(uniform, array);
  12804. };
  12805. Engine.prototype.setIntArray2 = function (uniform, array) {
  12806. if (!uniform || array.length % 2 !== 0)
  12807. return;
  12808. this._gl.uniform2iv(uniform, array);
  12809. };
  12810. Engine.prototype.setIntArray3 = function (uniform, array) {
  12811. if (!uniform || array.length % 3 !== 0)
  12812. return;
  12813. this._gl.uniform3iv(uniform, array);
  12814. };
  12815. Engine.prototype.setIntArray4 = function (uniform, array) {
  12816. if (!uniform || array.length % 4 !== 0)
  12817. return;
  12818. this._gl.uniform4iv(uniform, array);
  12819. };
  12820. Engine.prototype.setFloatArray = function (uniform, array) {
  12821. if (!uniform)
  12822. return;
  12823. this._gl.uniform1fv(uniform, array);
  12824. };
  12825. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12826. if (!uniform || array.length % 2 !== 0)
  12827. return;
  12828. this._gl.uniform2fv(uniform, array);
  12829. };
  12830. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12831. if (!uniform || array.length % 3 !== 0)
  12832. return;
  12833. this._gl.uniform3fv(uniform, array);
  12834. };
  12835. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12836. if (!uniform || array.length % 4 !== 0)
  12837. return;
  12838. this._gl.uniform4fv(uniform, array);
  12839. };
  12840. Engine.prototype.setArray = function (uniform, array) {
  12841. if (!uniform)
  12842. return;
  12843. this._gl.uniform1fv(uniform, array);
  12844. };
  12845. Engine.prototype.setArray2 = function (uniform, array) {
  12846. if (!uniform || array.length % 2 !== 0)
  12847. return;
  12848. this._gl.uniform2fv(uniform, array);
  12849. };
  12850. Engine.prototype.setArray3 = function (uniform, array) {
  12851. if (!uniform || array.length % 3 !== 0)
  12852. return;
  12853. this._gl.uniform3fv(uniform, array);
  12854. };
  12855. Engine.prototype.setArray4 = function (uniform, array) {
  12856. if (!uniform || array.length % 4 !== 0)
  12857. return;
  12858. this._gl.uniform4fv(uniform, array);
  12859. };
  12860. Engine.prototype.setMatrices = function (uniform, matrices) {
  12861. if (!uniform)
  12862. return;
  12863. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12864. };
  12865. Engine.prototype.setMatrix = function (uniform, matrix) {
  12866. if (!uniform)
  12867. return;
  12868. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12869. };
  12870. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12871. if (!uniform)
  12872. return;
  12873. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12874. };
  12875. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12876. if (!uniform)
  12877. return;
  12878. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12879. };
  12880. Engine.prototype.setInt = function (uniform, value) {
  12881. if (!uniform)
  12882. return;
  12883. this._gl.uniform1i(uniform, value);
  12884. };
  12885. Engine.prototype.setFloat = function (uniform, value) {
  12886. if (!uniform)
  12887. return;
  12888. this._gl.uniform1f(uniform, value);
  12889. };
  12890. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12891. if (!uniform)
  12892. return;
  12893. this._gl.uniform2f(uniform, x, y);
  12894. };
  12895. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12896. if (!uniform)
  12897. return;
  12898. this._gl.uniform3f(uniform, x, y, z);
  12899. };
  12900. Engine.prototype.setBool = function (uniform, bool) {
  12901. if (!uniform)
  12902. return;
  12903. this._gl.uniform1i(uniform, bool);
  12904. };
  12905. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12906. if (!uniform)
  12907. return;
  12908. this._gl.uniform4f(uniform, x, y, z, w);
  12909. };
  12910. Engine.prototype.setColor3 = function (uniform, color3) {
  12911. if (!uniform)
  12912. return;
  12913. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12914. };
  12915. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12916. if (!uniform)
  12917. return;
  12918. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12919. };
  12920. /**
  12921. * Sets a Color4 on a uniform variable
  12922. * @param uniform defines the uniform location
  12923. * @param color4 defines the value to be set
  12924. */
  12925. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12926. if (!uniform)
  12927. return;
  12928. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12929. };
  12930. // States
  12931. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12932. if (zOffset === void 0) { zOffset = 0; }
  12933. if (reverseSide === void 0) { reverseSide = false; }
  12934. // Culling
  12935. if (this._depthCullingState.cull !== culling || force) {
  12936. this._depthCullingState.cull = culling;
  12937. }
  12938. // Cull face
  12939. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12940. if (this._depthCullingState.cullFace !== cullFace || force) {
  12941. this._depthCullingState.cullFace = cullFace;
  12942. }
  12943. // Z offset
  12944. this.setZOffset(zOffset);
  12945. // Front face
  12946. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12947. if (this._depthCullingState.frontFace !== frontFace || force) {
  12948. this._depthCullingState.frontFace = frontFace;
  12949. }
  12950. };
  12951. Engine.prototype.setZOffset = function (value) {
  12952. this._depthCullingState.zOffset = value;
  12953. };
  12954. Engine.prototype.getZOffset = function () {
  12955. return this._depthCullingState.zOffset;
  12956. };
  12957. Engine.prototype.setDepthBuffer = function (enable) {
  12958. this._depthCullingState.depthTest = enable;
  12959. };
  12960. Engine.prototype.getDepthWrite = function () {
  12961. return this._depthCullingState.depthMask;
  12962. };
  12963. Engine.prototype.setDepthWrite = function (enable) {
  12964. this._depthCullingState.depthMask = enable;
  12965. };
  12966. Engine.prototype.setColorWrite = function (enable) {
  12967. this._gl.colorMask(enable, enable, enable, enable);
  12968. this._colorWrite = enable;
  12969. };
  12970. Engine.prototype.getColorWrite = function () {
  12971. return this._colorWrite;
  12972. };
  12973. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12974. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12975. };
  12976. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12977. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12978. if (this._alphaMode === mode) {
  12979. return;
  12980. }
  12981. switch (mode) {
  12982. case Engine.ALPHA_DISABLE:
  12983. this._alphaState.alphaBlend = false;
  12984. break;
  12985. case Engine.ALPHA_PREMULTIPLIED:
  12986. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12987. this._alphaState.alphaBlend = true;
  12988. break;
  12989. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12990. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12991. this._alphaState.alphaBlend = true;
  12992. break;
  12993. case Engine.ALPHA_COMBINE:
  12994. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12995. this._alphaState.alphaBlend = true;
  12996. break;
  12997. case Engine.ALPHA_ONEONE:
  12998. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12999. this._alphaState.alphaBlend = true;
  13000. break;
  13001. case Engine.ALPHA_ADD:
  13002. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13003. this._alphaState.alphaBlend = true;
  13004. break;
  13005. case Engine.ALPHA_SUBTRACT:
  13006. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13007. this._alphaState.alphaBlend = true;
  13008. break;
  13009. case Engine.ALPHA_MULTIPLY:
  13010. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  13011. this._alphaState.alphaBlend = true;
  13012. break;
  13013. case Engine.ALPHA_MAXIMIZED:
  13014. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13015. this._alphaState.alphaBlend = true;
  13016. break;
  13017. case Engine.ALPHA_INTERPOLATE:
  13018. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  13019. this._alphaState.alphaBlend = true;
  13020. break;
  13021. case Engine.ALPHA_SCREENMODE:
  13022. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13023. this._alphaState.alphaBlend = true;
  13024. break;
  13025. }
  13026. if (!noDepthWriteChange) {
  13027. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  13028. }
  13029. this._alphaMode = mode;
  13030. };
  13031. Engine.prototype.getAlphaMode = function () {
  13032. return this._alphaMode;
  13033. };
  13034. // Textures
  13035. Engine.prototype.wipeCaches = function (bruteForce) {
  13036. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  13037. return;
  13038. }
  13039. this._currentEffect = null;
  13040. // 6/8/2017: deltakosh: Should not be required anymore.
  13041. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  13042. if (bruteForce) {
  13043. this.resetTextureCache();
  13044. this._currentProgram = null;
  13045. this._stencilState.reset();
  13046. this._depthCullingState.reset();
  13047. this.setDepthFunctionToLessOrEqual();
  13048. this._alphaState.reset();
  13049. }
  13050. this._resetVertexBufferBinding();
  13051. this._cachedIndexBuffer = null;
  13052. this._cachedEffectForVertexBuffers = null;
  13053. this._unbindVertexArrayObject();
  13054. this.bindIndexBuffer(null);
  13055. };
  13056. /**
  13057. * Set the compressed texture format to use, based on the formats you have, and the formats
  13058. * supported by the hardware / browser.
  13059. *
  13060. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  13061. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  13062. * to API arguments needed to compressed textures. This puts the burden on the container
  13063. * generator to house the arcane code for determining these for current & future formats.
  13064. *
  13065. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  13066. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  13067. *
  13068. * Note: The result of this call is not taken into account when a texture is base64.
  13069. *
  13070. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  13071. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13072. *
  13073. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13074. * @returns The extension selected.
  13075. */
  13076. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13077. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13078. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13079. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13080. return this._textureFormatInUse = this._texturesSupported[i];
  13081. }
  13082. }
  13083. }
  13084. // actively set format to nothing, to allow this to be called more than once
  13085. // and possibly fail the 2nd time
  13086. this._textureFormatInUse = null;
  13087. return null;
  13088. };
  13089. Engine.prototype._createTexture = function () {
  13090. var texture = this._gl.createTexture();
  13091. if (!texture) {
  13092. throw new Error("Unable to create texture");
  13093. }
  13094. return texture;
  13095. };
  13096. /**
  13097. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  13098. * @param {string} urlArg- This contains one of the following:
  13099. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13100. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13101. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13102. *
  13103. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13104. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13105. * @param {Scene} scene- Needed for loading to the correct scene.
  13106. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13107. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13108. * @param {callback} onError- Optional callback to be called upon failure.
  13109. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13110. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13111. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13112. *
  13113. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13114. */
  13115. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13116. var _this = this;
  13117. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13118. if (onLoad === void 0) { onLoad = null; }
  13119. if (onError === void 0) { onError = null; }
  13120. if (buffer === void 0) { buffer = null; }
  13121. if (fallBack === void 0) { fallBack = null; }
  13122. if (format === void 0) { format = null; }
  13123. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13124. var fromData = url.substr(0, 5) === "data:";
  13125. var fromBlob = url.substr(0, 5) === "blob:";
  13126. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13127. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13128. // establish the file extension, if possible
  13129. var lastDot = url.lastIndexOf('.');
  13130. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13131. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13132. var isTGA = (extension.indexOf(".tga") === 0);
  13133. // determine if a ktx file should be substituted
  13134. var isKTX = false;
  13135. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13136. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13137. isKTX = true;
  13138. }
  13139. if (scene) {
  13140. scene._addPendingData(texture);
  13141. }
  13142. texture.url = url;
  13143. texture.generateMipMaps = !noMipmap;
  13144. texture.samplingMode = samplingMode;
  13145. texture.invertY = invertY;
  13146. if (!this._doNotHandleContextLost) {
  13147. // Keep a link to the buffer only if we plan to handle context lost
  13148. texture._buffer = buffer;
  13149. }
  13150. var onLoadObserver = null;
  13151. if (onLoad && !fallBack) {
  13152. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13153. }
  13154. if (!fallBack)
  13155. this._internalTexturesCache.push(texture);
  13156. var onerror = function (message, exception) {
  13157. if (scene) {
  13158. scene._removePendingData(texture);
  13159. }
  13160. if (onLoadObserver) {
  13161. texture.onLoadedObservable.remove(onLoadObserver);
  13162. }
  13163. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13164. if (isKTX) {
  13165. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13166. }
  13167. else if (BABYLON.Tools.UseFallbackTexture) {
  13168. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13169. }
  13170. if (onError) {
  13171. onError(message || "Unknown error", exception);
  13172. }
  13173. };
  13174. var callback = null;
  13175. // processing for non-image formats
  13176. if (isKTX || isTGA || isDDS) {
  13177. if (isKTX) {
  13178. callback = function (data) {
  13179. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13180. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13181. ktx.uploadLevels(_this._gl, !noMipmap);
  13182. return false;
  13183. }, samplingMode);
  13184. };
  13185. }
  13186. else if (isTGA) {
  13187. callback = function (arrayBuffer) {
  13188. var data = new Uint8Array(arrayBuffer);
  13189. var header = BABYLON.TGATools.GetTGAHeader(data);
  13190. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13191. BABYLON.TGATools.UploadContent(_this._gl, data);
  13192. return false;
  13193. }, samplingMode);
  13194. };
  13195. }
  13196. else if (isDDS) {
  13197. callback = function (data) {
  13198. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13199. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13200. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13201. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13202. return false;
  13203. }, samplingMode);
  13204. };
  13205. }
  13206. if (!buffer) {
  13207. this._loadFile(url, function (data) {
  13208. if (callback) {
  13209. callback(data);
  13210. }
  13211. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13212. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13213. });
  13214. }
  13215. else {
  13216. if (callback) {
  13217. callback(buffer);
  13218. }
  13219. }
  13220. // image format processing
  13221. }
  13222. else {
  13223. var onload = function (img) {
  13224. if (fromBlob && !_this._doNotHandleContextLost) {
  13225. // We need to store the image if we need to rebuild the texture
  13226. // in case of a webgl context lost
  13227. texture._buffer = img;
  13228. }
  13229. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13230. var gl = _this._gl;
  13231. var isPot = (img.width === potWidth && img.height === potHeight);
  13232. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13233. if (isPot) {
  13234. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13235. return false;
  13236. }
  13237. // Using shaders to rescale because canvas.drawImage is lossy
  13238. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13239. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13240. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13241. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13242. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13243. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13244. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13245. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13246. _this._releaseTexture(source);
  13247. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13248. continuationCallback();
  13249. });
  13250. return true;
  13251. }, samplingMode);
  13252. };
  13253. if (!fromData || isBase64)
  13254. if (buffer instanceof HTMLImageElement) {
  13255. onload(buffer);
  13256. }
  13257. else {
  13258. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13259. }
  13260. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13261. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13262. else
  13263. onload(buffer);
  13264. }
  13265. return texture;
  13266. };
  13267. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13268. var _this = this;
  13269. var rtt = this.createRenderTargetTexture({
  13270. width: destination.width,
  13271. height: destination.height,
  13272. }, {
  13273. generateMipMaps: false,
  13274. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13275. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13276. generateDepthBuffer: false,
  13277. generateStencilBuffer: false
  13278. });
  13279. if (!this._rescalePostProcess) {
  13280. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13281. }
  13282. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13283. _this._rescalePostProcess.onApply = function (effect) {
  13284. effect._bindTexture("textureSampler", source);
  13285. };
  13286. var hostingScene = scene;
  13287. if (!hostingScene) {
  13288. hostingScene = _this.scenes[_this.scenes.length - 1];
  13289. }
  13290. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13291. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13292. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13293. _this.unBindFramebuffer(rtt);
  13294. _this._releaseTexture(rtt);
  13295. if (onComplete) {
  13296. onComplete();
  13297. }
  13298. });
  13299. };
  13300. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13301. if (compression === void 0) { compression = null; }
  13302. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13303. if (!texture) {
  13304. return;
  13305. }
  13306. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13307. var internalFormat = this._getInternalFormat(format);
  13308. var textureType = this._getWebGLTextureType(type);
  13309. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13310. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13311. if (!this._doNotHandleContextLost) {
  13312. texture._bufferView = data;
  13313. texture.format = format;
  13314. texture.type = type;
  13315. texture.invertY = invertY;
  13316. texture._compression = compression;
  13317. }
  13318. if (texture.width % 4 !== 0) {
  13319. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13320. }
  13321. if (compression && data) {
  13322. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13323. }
  13324. else {
  13325. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13326. }
  13327. if (texture.generateMipMaps) {
  13328. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13329. }
  13330. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13331. // this.resetTextureCache();
  13332. texture.isReady = true;
  13333. };
  13334. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13335. if (compression === void 0) { compression = null; }
  13336. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13337. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13338. texture.baseWidth = width;
  13339. texture.baseHeight = height;
  13340. texture.width = width;
  13341. texture.height = height;
  13342. texture.format = format;
  13343. texture.generateMipMaps = generateMipMaps;
  13344. texture.samplingMode = samplingMode;
  13345. texture.invertY = invertY;
  13346. texture._compression = compression;
  13347. texture.type = type;
  13348. if (!this._doNotHandleContextLost) {
  13349. texture._bufferView = data;
  13350. }
  13351. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13352. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13353. // Filters
  13354. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13355. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13356. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13357. if (generateMipMaps) {
  13358. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13359. }
  13360. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13361. this._internalTexturesCache.push(texture);
  13362. return texture;
  13363. };
  13364. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13365. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13366. texture.baseWidth = width;
  13367. texture.baseHeight = height;
  13368. if (generateMipMaps) {
  13369. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13370. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13371. }
  13372. // this.resetTextureCache();
  13373. texture.width = width;
  13374. texture.height = height;
  13375. texture.isReady = false;
  13376. texture.generateMipMaps = generateMipMaps;
  13377. texture.samplingMode = samplingMode;
  13378. this.updateTextureSamplingMode(samplingMode, texture);
  13379. this._internalTexturesCache.push(texture);
  13380. return texture;
  13381. };
  13382. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13383. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13384. if (texture.isCube) {
  13385. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13386. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13387. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13388. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13389. }
  13390. else if (texture.is3D) {
  13391. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13392. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13393. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13394. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13395. }
  13396. else {
  13397. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13398. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13399. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13400. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13401. }
  13402. texture.samplingMode = samplingMode;
  13403. };
  13404. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13405. if (premulAlpha === void 0) { premulAlpha = false; }
  13406. if (!texture) {
  13407. return;
  13408. }
  13409. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13410. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13411. if (premulAlpha) {
  13412. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13413. }
  13414. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13415. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13416. if (texture.generateMipMaps) {
  13417. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13418. }
  13419. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13420. if (premulAlpha) {
  13421. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13422. }
  13423. texture.isReady = true;
  13424. };
  13425. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13426. if (!texture || texture._isDisabled) {
  13427. return;
  13428. }
  13429. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13430. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13431. try {
  13432. // Testing video texture support
  13433. if (this._videoTextureSupported === undefined) {
  13434. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13435. if (this._gl.getError() !== 0) {
  13436. this._videoTextureSupported = false;
  13437. }
  13438. else {
  13439. this._videoTextureSupported = true;
  13440. }
  13441. }
  13442. // Copy video through the current working canvas if video texture is not supported
  13443. if (!this._videoTextureSupported) {
  13444. if (!texture._workingCanvas) {
  13445. texture._workingCanvas = document.createElement("canvas");
  13446. var context = texture._workingCanvas.getContext("2d");
  13447. if (!context) {
  13448. throw new Error("Unable to get 2d context");
  13449. }
  13450. texture._workingContext = context;
  13451. texture._workingCanvas.width = texture.width;
  13452. texture._workingCanvas.height = texture.height;
  13453. }
  13454. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13455. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13456. }
  13457. else {
  13458. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13459. }
  13460. if (texture.generateMipMaps) {
  13461. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13462. }
  13463. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13464. // this.resetTextureCache();
  13465. texture.isReady = true;
  13466. }
  13467. catch (ex) {
  13468. // Something unexpected
  13469. // Let's disable the texture
  13470. texture._isDisabled = true;
  13471. }
  13472. };
  13473. /**
  13474. * Updates a depth texture Comparison Mode and Function.
  13475. * If the comparison Function is equal to 0, the mode will be set to none.
  13476. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13477. * @param texture The texture to set the comparison function for
  13478. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13479. */
  13480. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13481. if (this.webGLVersion === 1) {
  13482. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13483. return;
  13484. }
  13485. var gl = this._gl;
  13486. if (texture.isCube) {
  13487. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13488. if (comparisonFunction === 0) {
  13489. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13490. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13491. }
  13492. else {
  13493. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13494. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13495. }
  13496. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13497. }
  13498. else {
  13499. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13500. if (comparisonFunction === 0) {
  13501. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13502. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13503. }
  13504. else {
  13505. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13506. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13507. }
  13508. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13509. }
  13510. texture._comparisonFunction = comparisonFunction;
  13511. };
  13512. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13513. var width = size.width || size;
  13514. var height = size.height || size;
  13515. internalTexture.baseWidth = width;
  13516. internalTexture.baseHeight = height;
  13517. internalTexture.width = width;
  13518. internalTexture.height = height;
  13519. internalTexture.isReady = true;
  13520. internalTexture.samples = 1;
  13521. internalTexture.generateMipMaps = false;
  13522. internalTexture._generateDepthBuffer = true;
  13523. internalTexture._generateStencilBuffer = generateStencil;
  13524. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13525. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13526. internalTexture._comparisonFunction = comparisonFunction;
  13527. var gl = this._gl;
  13528. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13529. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13530. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13531. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13532. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13533. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13534. if (comparisonFunction === 0) {
  13535. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13536. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13537. }
  13538. else {
  13539. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13540. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13541. }
  13542. };
  13543. /**
  13544. * Creates a depth stencil texture.
  13545. * This is only available in WebGL 2 or with the depth texture extension available.
  13546. * @param size The size of face edge in the texture.
  13547. * @param options The options defining the texture.
  13548. * @returns The texture
  13549. */
  13550. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13551. if (options.isCube) {
  13552. var width = size.width || size;
  13553. return this._createDepthStencilCubeTexture(width, options);
  13554. }
  13555. else {
  13556. return this._createDepthStencilTexture(size, options);
  13557. }
  13558. };
  13559. /**
  13560. * Creates a depth stencil texture.
  13561. * This is only available in WebGL 2 or with the depth texture extension available.
  13562. * @param size The size of face edge in the texture.
  13563. * @param options The options defining the texture.
  13564. * @returns The texture
  13565. */
  13566. Engine.prototype._createDepthStencilTexture = function (size, options) {
  13567. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13568. if (!this._caps.depthTextureExtension) {
  13569. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13570. return internalTexture;
  13571. }
  13572. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13573. var gl = this._gl;
  13574. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13575. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13576. if (this.webGLVersion > 1) {
  13577. if (internalOptions.generateStencil) {
  13578. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13579. }
  13580. else {
  13581. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13582. }
  13583. }
  13584. else {
  13585. if (internalOptions.generateStencil) {
  13586. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13587. }
  13588. else {
  13589. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13590. }
  13591. }
  13592. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13593. return internalTexture;
  13594. };
  13595. /**
  13596. * Creates a depth stencil cube texture.
  13597. * This is only available in WebGL 2.
  13598. * @param size The size of face edge in the cube texture.
  13599. * @param options The options defining the cube texture.
  13600. * @returns The cube texture
  13601. */
  13602. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  13603. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13604. internalTexture.isCube = true;
  13605. if (this.webGLVersion === 1) {
  13606. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13607. return internalTexture;
  13608. }
  13609. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13610. var gl = this._gl;
  13611. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13612. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13613. // Create the depth/stencil buffer
  13614. for (var face = 0; face < 6; face++) {
  13615. if (internalOptions.generateStencil) {
  13616. 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);
  13617. }
  13618. else {
  13619. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13620. }
  13621. }
  13622. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13623. return internalTexture;
  13624. };
  13625. /**
  13626. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13627. * @param renderTarget The render target to set the frame buffer for
  13628. */
  13629. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13630. // Create the framebuffer
  13631. var internalTexture = renderTarget.getInternalTexture();
  13632. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13633. return;
  13634. }
  13635. var gl = this._gl;
  13636. var depthStencilTexture = renderTarget.depthStencilTexture;
  13637. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13638. if (depthStencilTexture.isCube) {
  13639. if (depthStencilTexture._generateStencilBuffer) {
  13640. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13641. }
  13642. else {
  13643. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13644. }
  13645. }
  13646. else {
  13647. if (depthStencilTexture._generateStencilBuffer) {
  13648. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13649. }
  13650. else {
  13651. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13652. }
  13653. }
  13654. this.bindUnboundFramebuffer(null);
  13655. };
  13656. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13657. var fullOptions = new RenderTargetCreationOptions();
  13658. if (options !== undefined && typeof options === "object") {
  13659. fullOptions.generateMipMaps = options.generateMipMaps;
  13660. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13661. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13662. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13663. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13664. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13665. }
  13666. else {
  13667. fullOptions.generateMipMaps = options;
  13668. fullOptions.generateDepthBuffer = true;
  13669. fullOptions.generateStencilBuffer = false;
  13670. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13671. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13672. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13673. }
  13674. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13675. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13676. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13677. }
  13678. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13679. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13680. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13681. }
  13682. var gl = this._gl;
  13683. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13684. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13685. var width = size.width || size;
  13686. var height = size.height || size;
  13687. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13688. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13689. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13690. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13691. }
  13692. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13693. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13694. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13695. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13696. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13697. // Create the framebuffer
  13698. var framebuffer = gl.createFramebuffer();
  13699. this.bindUnboundFramebuffer(framebuffer);
  13700. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13701. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13702. if (fullOptions.generateMipMaps) {
  13703. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13704. }
  13705. // Unbind
  13706. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13707. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13708. this.bindUnboundFramebuffer(null);
  13709. texture._framebuffer = framebuffer;
  13710. texture.baseWidth = width;
  13711. texture.baseHeight = height;
  13712. texture.width = width;
  13713. texture.height = height;
  13714. texture.isReady = true;
  13715. texture.samples = 1;
  13716. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13717. texture.samplingMode = fullOptions.samplingMode;
  13718. texture.type = fullOptions.type;
  13719. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13720. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13721. // this.resetTextureCache();
  13722. this._internalTexturesCache.push(texture);
  13723. return texture;
  13724. };
  13725. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13726. var generateMipMaps = false;
  13727. var generateDepthBuffer = true;
  13728. var generateStencilBuffer = false;
  13729. var generateDepthTexture = false;
  13730. var textureCount = 1;
  13731. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13732. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13733. var types = [], samplingModes = [];
  13734. if (options !== undefined) {
  13735. generateMipMaps = options.generateMipMaps;
  13736. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13737. generateStencilBuffer = options.generateStencilBuffer;
  13738. generateDepthTexture = options.generateDepthTexture;
  13739. textureCount = options.textureCount || 1;
  13740. if (options.types) {
  13741. types = options.types;
  13742. }
  13743. if (options.samplingModes) {
  13744. samplingModes = options.samplingModes;
  13745. }
  13746. }
  13747. var gl = this._gl;
  13748. // Create the framebuffer
  13749. var framebuffer = gl.createFramebuffer();
  13750. this.bindUnboundFramebuffer(framebuffer);
  13751. var width = size.width || size;
  13752. var height = size.height || size;
  13753. var textures = [];
  13754. var attachments = [];
  13755. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13756. for (var i = 0; i < textureCount; i++) {
  13757. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13758. var type = types[i] || defaultType;
  13759. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13760. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13761. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13762. }
  13763. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13764. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13765. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13766. }
  13767. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13768. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13769. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13770. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13771. }
  13772. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13773. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13774. textures.push(texture);
  13775. attachments.push(attachment);
  13776. gl.activeTexture(gl["TEXTURE" + i]);
  13777. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13778. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13779. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13780. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13781. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13782. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13783. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13784. if (generateMipMaps) {
  13785. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13786. }
  13787. // Unbind
  13788. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13789. texture._framebuffer = framebuffer;
  13790. texture._depthStencilBuffer = depthStencilBuffer;
  13791. texture.baseWidth = width;
  13792. texture.baseHeight = height;
  13793. texture.width = width;
  13794. texture.height = height;
  13795. texture.isReady = true;
  13796. texture.samples = 1;
  13797. texture.generateMipMaps = generateMipMaps;
  13798. texture.samplingMode = samplingMode;
  13799. texture.type = type;
  13800. texture._generateDepthBuffer = generateDepthBuffer;
  13801. texture._generateStencilBuffer = generateStencilBuffer;
  13802. texture._attachments = attachments;
  13803. this._internalTexturesCache.push(texture);
  13804. }
  13805. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13806. // Depth texture
  13807. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13808. gl.activeTexture(gl.TEXTURE0);
  13809. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13810. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13811. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13812. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13813. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13814. 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);
  13815. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13816. depthTexture._framebuffer = framebuffer;
  13817. depthTexture.baseWidth = width;
  13818. depthTexture.baseHeight = height;
  13819. depthTexture.width = width;
  13820. depthTexture.height = height;
  13821. depthTexture.isReady = true;
  13822. depthTexture.samples = 1;
  13823. depthTexture.generateMipMaps = generateMipMaps;
  13824. depthTexture.samplingMode = gl.NEAREST;
  13825. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13826. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13827. textures.push(depthTexture);
  13828. this._internalTexturesCache.push(depthTexture);
  13829. }
  13830. gl.drawBuffers(attachments);
  13831. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13832. this.bindUnboundFramebuffer(null);
  13833. this.resetTextureCache();
  13834. return textures;
  13835. };
  13836. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13837. if (samples === void 0) { samples = 1; }
  13838. var depthStencilBuffer = null;
  13839. var gl = this._gl;
  13840. // Create the depth/stencil buffer
  13841. if (generateStencilBuffer) {
  13842. depthStencilBuffer = gl.createRenderbuffer();
  13843. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13844. if (samples > 1) {
  13845. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13846. }
  13847. else {
  13848. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13849. }
  13850. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13851. }
  13852. else if (generateDepthBuffer) {
  13853. depthStencilBuffer = gl.createRenderbuffer();
  13854. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13855. if (samples > 1) {
  13856. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13857. }
  13858. else {
  13859. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13860. }
  13861. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13862. }
  13863. return depthStencilBuffer;
  13864. };
  13865. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13866. if (this.webGLVersion < 2 || !texture) {
  13867. return 1;
  13868. }
  13869. if (texture.samples === samples) {
  13870. return samples;
  13871. }
  13872. var gl = this._gl;
  13873. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13874. // Dispose previous render buffers
  13875. if (texture._depthStencilBuffer) {
  13876. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13877. texture._depthStencilBuffer = null;
  13878. }
  13879. if (texture._MSAAFramebuffer) {
  13880. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13881. texture._MSAAFramebuffer = null;
  13882. }
  13883. if (texture._MSAARenderBuffer) {
  13884. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13885. texture._MSAARenderBuffer = null;
  13886. }
  13887. if (samples > 1) {
  13888. var framebuffer = gl.createFramebuffer();
  13889. if (!framebuffer) {
  13890. throw new Error("Unable to create multi sampled framebuffer");
  13891. }
  13892. texture._MSAAFramebuffer = framebuffer;
  13893. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13894. var colorRenderbuffer = gl.createRenderbuffer();
  13895. if (!colorRenderbuffer) {
  13896. throw new Error("Unable to create multi sampled framebuffer");
  13897. }
  13898. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13899. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13900. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13901. texture._MSAARenderBuffer = colorRenderbuffer;
  13902. }
  13903. else {
  13904. this.bindUnboundFramebuffer(texture._framebuffer);
  13905. }
  13906. texture.samples = samples;
  13907. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13908. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13909. this.bindUnboundFramebuffer(null);
  13910. return samples;
  13911. };
  13912. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13913. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13914. return 1;
  13915. }
  13916. if (textures[0].samples === samples) {
  13917. return samples;
  13918. }
  13919. var gl = this._gl;
  13920. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13921. // Dispose previous render buffers
  13922. if (textures[0]._depthStencilBuffer) {
  13923. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13924. textures[0]._depthStencilBuffer = null;
  13925. }
  13926. if (textures[0]._MSAAFramebuffer) {
  13927. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13928. textures[0]._MSAAFramebuffer = null;
  13929. }
  13930. for (var i = 0; i < textures.length; i++) {
  13931. if (textures[i]._MSAARenderBuffer) {
  13932. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13933. textures[i]._MSAARenderBuffer = null;
  13934. }
  13935. }
  13936. if (samples > 1) {
  13937. var framebuffer = gl.createFramebuffer();
  13938. if (!framebuffer) {
  13939. throw new Error("Unable to create multi sampled framebuffer");
  13940. }
  13941. this.bindUnboundFramebuffer(framebuffer);
  13942. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13943. var attachments = [];
  13944. for (var i = 0; i < textures.length; i++) {
  13945. var texture = textures[i];
  13946. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13947. var colorRenderbuffer = gl.createRenderbuffer();
  13948. if (!colorRenderbuffer) {
  13949. throw new Error("Unable to create multi sampled framebuffer");
  13950. }
  13951. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13952. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13953. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13954. texture._MSAAFramebuffer = framebuffer;
  13955. texture._MSAARenderBuffer = colorRenderbuffer;
  13956. texture.samples = samples;
  13957. texture._depthStencilBuffer = depthStencilBuffer;
  13958. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13959. attachments.push(attachment);
  13960. }
  13961. gl.drawBuffers(attachments);
  13962. }
  13963. else {
  13964. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13965. }
  13966. this.bindUnboundFramebuffer(null);
  13967. return samples;
  13968. };
  13969. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13970. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13971. };
  13972. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13973. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13974. };
  13975. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13976. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  13977. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13978. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13979. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13980. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13981. }
  13982. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13983. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13984. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13985. }
  13986. var gl = this._gl;
  13987. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13988. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13989. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13990. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13991. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13992. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13993. }
  13994. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13995. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13996. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13997. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13998. for (var face = 0; face < 6; face++) {
  13999. 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);
  14000. }
  14001. // Create the framebuffer
  14002. var framebuffer = gl.createFramebuffer();
  14003. this.bindUnboundFramebuffer(framebuffer);
  14004. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  14005. // MipMaps
  14006. if (fullOptions.generateMipMaps) {
  14007. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14008. }
  14009. // Unbind
  14010. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14011. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14012. this.bindUnboundFramebuffer(null);
  14013. texture._framebuffer = framebuffer;
  14014. texture.width = size;
  14015. texture.height = size;
  14016. texture.isReady = true;
  14017. texture.isCube = true;
  14018. texture.samples = 1;
  14019. texture.generateMipMaps = fullOptions.generateMipMaps;
  14020. texture.samplingMode = fullOptions.samplingMode;
  14021. texture.type = fullOptions.type;
  14022. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  14023. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  14024. this._internalTexturesCache.push(texture);
  14025. return texture;
  14026. };
  14027. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  14028. var _this = this;
  14029. if (onLoad === void 0) { onLoad = null; }
  14030. if (onError === void 0) { onError = null; }
  14031. if (forcedExtension === void 0) { forcedExtension = null; }
  14032. var callback = function (loadData) {
  14033. if (!loadData) {
  14034. if (onLoad) {
  14035. onLoad(null);
  14036. }
  14037. return;
  14038. }
  14039. var texture = loadData.texture;
  14040. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  14041. texture._lodGenerationScale = scale;
  14042. texture._lodGenerationOffset = offset;
  14043. if (_this._caps.textureLOD) {
  14044. // Do not add extra process if texture lod is supported.
  14045. if (onLoad) {
  14046. onLoad(texture);
  14047. }
  14048. return;
  14049. }
  14050. var mipSlices = 3;
  14051. var gl = _this._gl;
  14052. var width = loadData.width;
  14053. if (!width) {
  14054. return;
  14055. }
  14056. var textures = [];
  14057. for (var i = 0; i < mipSlices; i++) {
  14058. //compute LOD from even spacing in smoothness (matching shader calculation)
  14059. var smoothness = i / (mipSlices - 1);
  14060. var roughness = 1 - smoothness;
  14061. var minLODIndex = offset; // roughness = 0
  14062. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  14063. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  14064. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  14065. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14066. glTextureFromLod.isCube = true;
  14067. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14068. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14069. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14070. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14071. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14072. if (loadData.isDDS) {
  14073. var info = loadData.info;
  14074. var data = loadData.data;
  14075. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14076. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14077. }
  14078. else {
  14079. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14080. }
  14081. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14082. // Wrap in a base texture for easy binding.
  14083. var lodTexture = new BABYLON.BaseTexture(scene);
  14084. lodTexture.isCube = true;
  14085. lodTexture._texture = glTextureFromLod;
  14086. glTextureFromLod.isReady = true;
  14087. textures.push(lodTexture);
  14088. }
  14089. texture._lodTextureHigh = textures[2];
  14090. texture._lodTextureMid = textures[1];
  14091. texture._lodTextureLow = textures[0];
  14092. if (onLoad) {
  14093. onLoad(texture);
  14094. }
  14095. };
  14096. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14097. };
  14098. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14099. var _this = this;
  14100. if (onLoad === void 0) { onLoad = null; }
  14101. if (onError === void 0) { onError = null; }
  14102. if (forcedExtension === void 0) { forcedExtension = null; }
  14103. var gl = this._gl;
  14104. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14105. texture.isCube = true;
  14106. texture.url = rootUrl;
  14107. texture.generateMipMaps = !noMipmap;
  14108. if (!this._doNotHandleContextLost) {
  14109. texture._extension = forcedExtension;
  14110. texture._files = files;
  14111. }
  14112. var isKTX = false;
  14113. var isDDS = false;
  14114. var lastDot = rootUrl.lastIndexOf('.');
  14115. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14116. if (this._textureFormatInUse) {
  14117. extension = this._textureFormatInUse;
  14118. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14119. isKTX = true;
  14120. }
  14121. else {
  14122. isDDS = (extension === ".dds");
  14123. }
  14124. var onerror = function (request, exception) {
  14125. if (onError && request) {
  14126. onError(request.status + " " + request.statusText, exception);
  14127. }
  14128. };
  14129. if (isKTX) {
  14130. this._loadFile(rootUrl, function (data) {
  14131. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14132. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14133. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14134. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14135. ktx.uploadLevels(_this._gl, !noMipmap);
  14136. _this.setCubeMapTextureParams(gl, loadMipmap);
  14137. texture.width = ktx.pixelWidth;
  14138. texture.height = ktx.pixelHeight;
  14139. texture.isReady = true;
  14140. }, undefined, undefined, true, onerror);
  14141. }
  14142. else if (isDDS) {
  14143. if (files && files.length === 6) {
  14144. this._cascadeLoadFiles(scene, function (imgs) {
  14145. var info;
  14146. var loadMipmap = false;
  14147. var width = 0;
  14148. for (var index = 0; index < imgs.length; index++) {
  14149. var data = imgs[index];
  14150. info = BABYLON.DDSTools.GetDDSInfo(data);
  14151. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14152. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14153. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14154. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14155. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14156. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14157. }
  14158. texture.width = info.width;
  14159. texture.height = info.height;
  14160. texture.type = info.textureType;
  14161. width = info.width;
  14162. }
  14163. _this.setCubeMapTextureParams(gl, loadMipmap);
  14164. texture.isReady = true;
  14165. if (onLoad) {
  14166. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14167. }
  14168. }, files, onError);
  14169. }
  14170. else {
  14171. this._loadFile(rootUrl, function (data) {
  14172. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14173. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14174. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14175. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14176. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14177. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14178. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14179. }
  14180. _this.setCubeMapTextureParams(gl, loadMipmap);
  14181. texture.width = info.width;
  14182. texture.height = info.height;
  14183. texture.isReady = true;
  14184. texture.type = info.textureType;
  14185. if (onLoad) {
  14186. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14187. }
  14188. }, undefined, undefined, true, onerror);
  14189. }
  14190. }
  14191. else {
  14192. if (!files) {
  14193. throw new Error("Cannot load cubemap because files were not defined");
  14194. }
  14195. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14196. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14197. var height = width;
  14198. _this._prepareWorkingCanvas();
  14199. if (!_this._workingCanvas || !_this._workingContext) {
  14200. return;
  14201. }
  14202. _this._workingCanvas.width = width;
  14203. _this._workingCanvas.height = height;
  14204. var faces = [
  14205. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14206. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14207. ];
  14208. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14209. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14210. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14211. for (var index = 0; index < faces.length; index++) {
  14212. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14213. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14214. }
  14215. if (!noMipmap) {
  14216. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14217. }
  14218. _this.setCubeMapTextureParams(gl, !noMipmap);
  14219. texture.width = width;
  14220. texture.height = height;
  14221. texture.isReady = true;
  14222. if (format) {
  14223. texture.format = format;
  14224. }
  14225. texture.onLoadedObservable.notifyObservers(texture);
  14226. texture.onLoadedObservable.clear();
  14227. if (onLoad) {
  14228. onLoad();
  14229. }
  14230. }, files, onError);
  14231. }
  14232. this._internalTexturesCache.push(texture);
  14233. return texture;
  14234. };
  14235. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14236. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14237. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14238. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14239. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14240. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14241. // this.resetTextureCache();
  14242. };
  14243. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14244. if (compression === void 0) { compression = null; }
  14245. if (level === void 0) { level = 0; }
  14246. texture._bufferViewArray = data;
  14247. texture.format = format;
  14248. texture.type = type;
  14249. texture.invertY = invertY;
  14250. texture._compression = compression;
  14251. var gl = this._gl;
  14252. var textureType = this._getWebGLTextureType(type);
  14253. var internalFormat = this._getInternalFormat(format);
  14254. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14255. var needConversion = false;
  14256. if (internalFormat === gl.RGB) {
  14257. internalFormat = gl.RGBA;
  14258. needConversion = true;
  14259. }
  14260. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14261. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14262. if (texture.width % 4 !== 0) {
  14263. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14264. }
  14265. // Data are known to be in +X +Y +Z -X -Y -Z
  14266. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14267. var faceData = data[faceIndex];
  14268. if (compression) {
  14269. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14270. }
  14271. else {
  14272. if (needConversion) {
  14273. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14274. }
  14275. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14276. }
  14277. }
  14278. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14279. if (isPot && texture.generateMipMaps && level === 0) {
  14280. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14281. }
  14282. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14283. // this.resetTextureCache();
  14284. texture.isReady = true;
  14285. };
  14286. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14287. if (compression === void 0) { compression = null; }
  14288. var gl = this._gl;
  14289. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14290. texture.isCube = true;
  14291. texture.generateMipMaps = generateMipMaps;
  14292. texture.format = format;
  14293. texture.type = type;
  14294. if (!this._doNotHandleContextLost) {
  14295. texture._bufferViewArray = data;
  14296. }
  14297. var textureType = this._getWebGLTextureType(type);
  14298. var internalFormat = this._getInternalFormat(format);
  14299. if (internalFormat === gl.RGB) {
  14300. internalFormat = gl.RGBA;
  14301. }
  14302. var width = size;
  14303. var height = width;
  14304. texture.width = width;
  14305. texture.height = height;
  14306. // Double check on POT to generate Mips.
  14307. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14308. if (!isPot) {
  14309. generateMipMaps = false;
  14310. }
  14311. // Upload data if needed. The texture won't be ready until then.
  14312. if (data) {
  14313. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14314. }
  14315. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14316. // Filters
  14317. if (data && generateMipMaps) {
  14318. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14319. }
  14320. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14321. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14322. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14323. }
  14324. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14325. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14326. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14327. }
  14328. else {
  14329. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14330. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14331. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14332. }
  14333. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14334. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14335. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14336. return texture;
  14337. };
  14338. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14339. var _this = this;
  14340. if (onLoad === void 0) { onLoad = null; }
  14341. if (onError === void 0) { onError = null; }
  14342. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14343. if (invertY === void 0) { invertY = false; }
  14344. var gl = this._gl;
  14345. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14346. scene._addPendingData(texture);
  14347. texture.url = url;
  14348. this._internalTexturesCache.push(texture);
  14349. var onerror = function (request, exception) {
  14350. scene._removePendingData(texture);
  14351. if (onError && request) {
  14352. onError(request.status + " " + request.statusText, exception);
  14353. }
  14354. };
  14355. var internalCallback = function (data) {
  14356. var width = texture.width;
  14357. var faceDataArrays = callback(data);
  14358. if (!faceDataArrays) {
  14359. return;
  14360. }
  14361. if (mipmmapGenerator) {
  14362. var textureType = _this._getWebGLTextureType(type);
  14363. var internalFormat = _this._getInternalFormat(format);
  14364. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14365. var needConversion = false;
  14366. if (internalFormat === gl.RGB) {
  14367. internalFormat = gl.RGBA;
  14368. needConversion = true;
  14369. }
  14370. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14371. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14372. var mipData = mipmmapGenerator(faceDataArrays);
  14373. for (var level = 0; level < mipData.length; level++) {
  14374. var mipSize = width >> level;
  14375. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14376. var mipFaceData = mipData[level][faceIndex];
  14377. if (needConversion) {
  14378. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14379. }
  14380. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14381. }
  14382. }
  14383. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14384. }
  14385. else {
  14386. texture.generateMipMaps = !noMipmap;
  14387. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14388. }
  14389. texture.isReady = true;
  14390. // this.resetTextureCache();
  14391. scene._removePendingData(texture);
  14392. if (onLoad) {
  14393. onLoad();
  14394. }
  14395. };
  14396. this._loadFile(url, function (data) {
  14397. internalCallback(data);
  14398. }, undefined, scene.database, true, onerror);
  14399. return texture;
  14400. };
  14401. ;
  14402. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14403. if (compression === void 0) { compression = null; }
  14404. var internalFormat = this._getInternalFormat(format);
  14405. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14406. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14407. if (!this._doNotHandleContextLost) {
  14408. texture._bufferView = data;
  14409. texture.format = format;
  14410. texture.invertY = invertY;
  14411. texture._compression = compression;
  14412. }
  14413. if (texture.width % 4 !== 0) {
  14414. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14415. }
  14416. if (compression && data) {
  14417. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14418. }
  14419. else {
  14420. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14421. }
  14422. if (texture.generateMipMaps) {
  14423. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14424. }
  14425. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14426. // this.resetTextureCache();
  14427. texture.isReady = true;
  14428. };
  14429. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14430. if (compression === void 0) { compression = null; }
  14431. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14432. texture.baseWidth = width;
  14433. texture.baseHeight = height;
  14434. texture.baseDepth = depth;
  14435. texture.width = width;
  14436. texture.height = height;
  14437. texture.depth = depth;
  14438. texture.format = format;
  14439. texture.generateMipMaps = generateMipMaps;
  14440. texture.samplingMode = samplingMode;
  14441. texture.is3D = true;
  14442. if (!this._doNotHandleContextLost) {
  14443. texture._bufferView = data;
  14444. }
  14445. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14446. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14447. // Filters
  14448. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14449. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14450. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14451. if (generateMipMaps) {
  14452. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14453. }
  14454. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14455. this._internalTexturesCache.push(texture);
  14456. return texture;
  14457. };
  14458. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14459. var gl = this._gl;
  14460. if (!gl) {
  14461. return;
  14462. }
  14463. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14464. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14465. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14466. if (!noMipmap && !isCompressed) {
  14467. gl.generateMipmap(gl.TEXTURE_2D);
  14468. }
  14469. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14470. // this.resetTextureCache();
  14471. if (scene) {
  14472. scene._removePendingData(texture);
  14473. }
  14474. texture.onLoadedObservable.notifyObservers(texture);
  14475. texture.onLoadedObservable.clear();
  14476. };
  14477. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14478. var _this = this;
  14479. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14480. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14481. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14482. var gl = this._gl;
  14483. if (!gl) {
  14484. return;
  14485. }
  14486. if (!texture._webGLTexture) {
  14487. // this.resetTextureCache();
  14488. if (scene) {
  14489. scene._removePendingData(texture);
  14490. }
  14491. return;
  14492. }
  14493. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14494. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14495. texture.baseWidth = width;
  14496. texture.baseHeight = height;
  14497. texture.width = potWidth;
  14498. texture.height = potHeight;
  14499. texture.isReady = true;
  14500. if (processFunction(potWidth, potHeight, function () {
  14501. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14502. })) {
  14503. // Returning as texture needs extra async steps
  14504. return;
  14505. }
  14506. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14507. };
  14508. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14509. // Create new RGBA data container.
  14510. var rgbaData;
  14511. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14512. rgbaData = new Float32Array(width * height * 4);
  14513. }
  14514. else {
  14515. rgbaData = new Uint32Array(width * height * 4);
  14516. }
  14517. // Convert each pixel.
  14518. for (var x = 0; x < width; x++) {
  14519. for (var y = 0; y < height; y++) {
  14520. var index = (y * width + x) * 3;
  14521. var newIndex = (y * width + x) * 4;
  14522. // Map Old Value to new value.
  14523. rgbaData[newIndex + 0] = rgbData[index + 0];
  14524. rgbaData[newIndex + 1] = rgbData[index + 1];
  14525. rgbaData[newIndex + 2] = rgbData[index + 2];
  14526. // Add fully opaque alpha channel.
  14527. rgbaData[newIndex + 3] = 1;
  14528. }
  14529. }
  14530. return rgbaData;
  14531. };
  14532. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14533. var gl = this._gl;
  14534. if (texture._framebuffer) {
  14535. gl.deleteFramebuffer(texture._framebuffer);
  14536. texture._framebuffer = null;
  14537. }
  14538. if (texture._depthStencilBuffer) {
  14539. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14540. texture._depthStencilBuffer = null;
  14541. }
  14542. if (texture._MSAAFramebuffer) {
  14543. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14544. texture._MSAAFramebuffer = null;
  14545. }
  14546. if (texture._MSAARenderBuffer) {
  14547. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14548. texture._MSAARenderBuffer = null;
  14549. }
  14550. };
  14551. Engine.prototype._releaseTexture = function (texture) {
  14552. var gl = this._gl;
  14553. this._releaseFramebufferObjects(texture);
  14554. gl.deleteTexture(texture._webGLTexture);
  14555. // Unbind channels
  14556. this.unbindAllTextures();
  14557. var index = this._internalTexturesCache.indexOf(texture);
  14558. if (index !== -1) {
  14559. this._internalTexturesCache.splice(index, 1);
  14560. }
  14561. // Integrated fixed lod samplers.
  14562. if (texture._lodTextureHigh) {
  14563. texture._lodTextureHigh.dispose();
  14564. }
  14565. if (texture._lodTextureMid) {
  14566. texture._lodTextureMid.dispose();
  14567. }
  14568. if (texture._lodTextureLow) {
  14569. texture._lodTextureLow.dispose();
  14570. }
  14571. // Set output texture of post process to null if the texture has been released/disposed
  14572. this.scenes.forEach(function (scene) {
  14573. scene.postProcesses.forEach(function (postProcess) {
  14574. if (postProcess._outputTexture == texture) {
  14575. postProcess._outputTexture = null;
  14576. }
  14577. });
  14578. scene.cameras.forEach(function (camera) {
  14579. camera._postProcesses.forEach(function (postProcess) {
  14580. if (postProcess) {
  14581. if (postProcess._outputTexture == texture) {
  14582. postProcess._outputTexture = null;
  14583. }
  14584. }
  14585. });
  14586. });
  14587. });
  14588. };
  14589. Engine.prototype.setProgram = function (program) {
  14590. if (this._currentProgram !== program) {
  14591. this._gl.useProgram(program);
  14592. this._currentProgram = program;
  14593. }
  14594. };
  14595. Engine.prototype.bindSamplers = function (effect) {
  14596. this.setProgram(effect.getProgram());
  14597. var samplers = effect.getSamplers();
  14598. for (var index = 0; index < samplers.length; index++) {
  14599. var uniform = effect.getUniform(samplers[index]);
  14600. if (uniform) {
  14601. this._boundUniforms[index] = uniform;
  14602. }
  14603. }
  14604. this._currentEffect = null;
  14605. };
  14606. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14607. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14608. return;
  14609. }
  14610. // Remove
  14611. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14612. // Bind last to it
  14613. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14614. // Bind to dummy
  14615. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14616. };
  14617. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14618. if (!internalTexture) {
  14619. return -1;
  14620. }
  14621. internalTexture._initialSlot = channel;
  14622. if (this.disableTextureBindingOptimization) {
  14623. if (channel !== internalTexture._designatedSlot) {
  14624. this._textureCollisions.addCount(1, false);
  14625. }
  14626. }
  14627. else {
  14628. if (channel !== internalTexture._designatedSlot) {
  14629. if (internalTexture._designatedSlot > -1) {
  14630. return internalTexture._designatedSlot;
  14631. }
  14632. else {
  14633. // No slot for this texture, let's pick a new one (if we find a free slot)
  14634. if (this._nextFreeTextureSlots.length) {
  14635. return this._nextFreeTextureSlots[0];
  14636. }
  14637. // We need to recycle the oldest bound texture, sorry.
  14638. this._textureCollisions.addCount(1, false);
  14639. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14640. }
  14641. }
  14642. }
  14643. return channel;
  14644. };
  14645. Engine.prototype._linkTrackers = function (previous, next) {
  14646. previous.next = next;
  14647. next.previous = previous;
  14648. };
  14649. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14650. var currentSlot = internalTexture._designatedSlot;
  14651. if (currentSlot === -1) {
  14652. return -1;
  14653. }
  14654. internalTexture._designatedSlot = -1;
  14655. if (this.disableTextureBindingOptimization) {
  14656. return -1;
  14657. }
  14658. // Remove from bound list
  14659. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14660. // Free the slot
  14661. this._boundTexturesCache[currentSlot] = null;
  14662. this._nextFreeTextureSlots.push(currentSlot);
  14663. return currentSlot;
  14664. };
  14665. Engine.prototype._activateCurrentTexture = function () {
  14666. if (this._currentTextureChannel !== this._activeChannel) {
  14667. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14668. this._currentTextureChannel = this._activeChannel;
  14669. }
  14670. };
  14671. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14672. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14673. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14674. this._activeChannel = texture._designatedSlot;
  14675. }
  14676. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14677. var isTextureForRendering = texture && texture._initialSlot > -1;
  14678. if (currentTextureBound !== texture) {
  14679. if (currentTextureBound) {
  14680. this._removeDesignatedSlot(currentTextureBound);
  14681. }
  14682. this._activateCurrentTexture();
  14683. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14684. this._boundTexturesCache[this._activeChannel] = texture;
  14685. if (texture) {
  14686. if (!this.disableTextureBindingOptimization) {
  14687. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14688. if (slotIndex > -1) {
  14689. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14690. }
  14691. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14692. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14693. }
  14694. texture._designatedSlot = this._activeChannel;
  14695. }
  14696. }
  14697. else if (forTextureDataUpdate) {
  14698. this._activateCurrentTexture();
  14699. }
  14700. if (isTextureForRendering && !forTextureDataUpdate) {
  14701. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14702. }
  14703. };
  14704. Engine.prototype._bindTexture = function (channel, texture) {
  14705. if (channel < 0) {
  14706. return;
  14707. }
  14708. if (texture) {
  14709. channel = this._getCorrectTextureChannel(channel, texture);
  14710. }
  14711. this._activeChannel = channel;
  14712. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14713. };
  14714. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14715. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14716. };
  14717. /**
  14718. * Binds the output of the passed in post process to the texture channel specified
  14719. * @param channel The channel the texture should be bound to
  14720. * @param postProcess The post process which's output should be bound
  14721. */
  14722. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  14723. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  14724. };
  14725. Engine.prototype.unbindAllTextures = function () {
  14726. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14727. this._activeChannel = channel;
  14728. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14729. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14730. if (this.webGLVersion > 1) {
  14731. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14732. }
  14733. }
  14734. };
  14735. /**
  14736. * Sets a texture to the according uniform.
  14737. * @param channel The texture channel
  14738. * @param uniform The uniform to set
  14739. * @param texture The texture to apply
  14740. */
  14741. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14742. if (channel < 0) {
  14743. return;
  14744. }
  14745. if (uniform) {
  14746. this._boundUniforms[channel] = uniform;
  14747. }
  14748. this._setTexture(channel, texture);
  14749. };
  14750. /**
  14751. * Sets a depth stencil texture from a render target to the according uniform.
  14752. * @param channel The texture channel
  14753. * @param uniform The uniform to set
  14754. * @param texture The render target texture containing the depth stencil texture to apply
  14755. */
  14756. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  14757. if (channel < 0) {
  14758. return;
  14759. }
  14760. if (uniform) {
  14761. this._boundUniforms[channel] = uniform;
  14762. }
  14763. if (!texture || !texture.depthStencilTexture) {
  14764. this._setTexture(channel, null);
  14765. }
  14766. else {
  14767. this._setTexture(channel, texture, false, true);
  14768. }
  14769. };
  14770. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14771. var uniform = this._boundUniforms[sourceSlot];
  14772. if (uniform._currentState === destination) {
  14773. return;
  14774. }
  14775. this._gl.uniform1i(uniform, destination);
  14776. uniform._currentState = destination;
  14777. };
  14778. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  14779. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14780. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  14781. // Not ready?
  14782. if (!texture) {
  14783. if (this._boundTexturesCache[channel] != null) {
  14784. this._activeChannel = channel;
  14785. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14786. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14787. if (this.webGLVersion > 1) {
  14788. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14789. }
  14790. }
  14791. return false;
  14792. }
  14793. // Video
  14794. if (texture.video) {
  14795. this._activeChannel = channel;
  14796. texture.update();
  14797. }
  14798. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14799. texture.delayLoad();
  14800. return false;
  14801. }
  14802. var internalTexture;
  14803. if (depthStencilTexture) {
  14804. internalTexture = texture.depthStencilTexture;
  14805. }
  14806. else if (texture.isReady()) {
  14807. internalTexture = texture.getInternalTexture();
  14808. }
  14809. else if (texture.isCube) {
  14810. internalTexture = this.emptyCubeTexture;
  14811. }
  14812. else if (texture.is3D) {
  14813. internalTexture = this.emptyTexture3D;
  14814. }
  14815. else {
  14816. internalTexture = this.emptyTexture;
  14817. }
  14818. if (!isPartOfTextureArray) {
  14819. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14820. }
  14821. if (this._boundTexturesCache[channel] === internalTexture) {
  14822. this._moveBoundTextureOnTop(internalTexture);
  14823. if (!isPartOfTextureArray) {
  14824. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14825. }
  14826. return false;
  14827. }
  14828. this._activeChannel = channel;
  14829. if (internalTexture && internalTexture.is3D) {
  14830. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14831. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14832. internalTexture._cachedWrapU = texture.wrapU;
  14833. switch (texture.wrapU) {
  14834. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14835. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14836. break;
  14837. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14838. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14839. break;
  14840. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14841. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14842. break;
  14843. }
  14844. }
  14845. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14846. internalTexture._cachedWrapV = texture.wrapV;
  14847. switch (texture.wrapV) {
  14848. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14849. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14850. break;
  14851. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14852. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14853. break;
  14854. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14855. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14856. break;
  14857. }
  14858. }
  14859. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14860. internalTexture._cachedWrapR = texture.wrapR;
  14861. switch (texture.wrapR) {
  14862. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14863. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14864. break;
  14865. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14866. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14867. break;
  14868. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14869. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14870. break;
  14871. }
  14872. }
  14873. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14874. }
  14875. else if (internalTexture && internalTexture.isCube) {
  14876. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14877. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14878. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14879. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14880. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14881. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14882. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14883. }
  14884. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14885. }
  14886. else {
  14887. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14888. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14889. internalTexture._cachedWrapU = texture.wrapU;
  14890. switch (texture.wrapU) {
  14891. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14892. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14893. break;
  14894. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14895. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14896. break;
  14897. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14898. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14899. break;
  14900. }
  14901. }
  14902. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14903. internalTexture._cachedWrapV = texture.wrapV;
  14904. switch (texture.wrapV) {
  14905. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14906. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14907. break;
  14908. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14909. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14910. break;
  14911. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14912. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14913. break;
  14914. }
  14915. }
  14916. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14917. }
  14918. return true;
  14919. };
  14920. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14921. if (channel < 0 || !uniform) {
  14922. return;
  14923. }
  14924. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14925. this._textureUnits = new Int32Array(textures.length);
  14926. }
  14927. for (var i = 0; i < textures.length; i++) {
  14928. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14929. }
  14930. this._gl.uniform1iv(uniform, this._textureUnits);
  14931. for (var index = 0; index < textures.length; index++) {
  14932. this._setTexture(this._textureUnits[index], textures[index], true);
  14933. }
  14934. };
  14935. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14936. var internalTexture = texture.getInternalTexture();
  14937. if (!internalTexture) {
  14938. return;
  14939. }
  14940. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14941. var value = texture.anisotropicFilteringLevel;
  14942. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14943. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14944. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14945. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14946. }
  14947. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14948. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14949. internalTexture._cachedAnisotropicFilteringLevel = value;
  14950. }
  14951. };
  14952. Engine.prototype.readPixels = function (x, y, width, height) {
  14953. var data = new Uint8Array(height * width * 4);
  14954. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14955. return data;
  14956. };
  14957. /**
  14958. * Add an externaly attached data from its key.
  14959. * This method call will fail and return false, if such key already exists.
  14960. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14961. * @param key the unique key that identifies the data
  14962. * @param data the data object to associate to the key for this Engine instance
  14963. * @return true if no such key were already present and the data was added successfully, false otherwise
  14964. */
  14965. Engine.prototype.addExternalData = function (key, data) {
  14966. if (!this._externalData) {
  14967. this._externalData = new BABYLON.StringDictionary();
  14968. }
  14969. return this._externalData.add(key, data);
  14970. };
  14971. /**
  14972. * Get an externaly attached data from its key
  14973. * @param key the unique key that identifies the data
  14974. * @return the associated data, if present (can be null), or undefined if not present
  14975. */
  14976. Engine.prototype.getExternalData = function (key) {
  14977. if (!this._externalData) {
  14978. this._externalData = new BABYLON.StringDictionary();
  14979. }
  14980. return this._externalData.get(key);
  14981. };
  14982. /**
  14983. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14984. * @param key the unique key that identifies the data
  14985. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14986. * @return the associated data, can be null if the factory returned null.
  14987. */
  14988. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14989. if (!this._externalData) {
  14990. this._externalData = new BABYLON.StringDictionary();
  14991. }
  14992. return this._externalData.getOrAddWithFactory(key, factory);
  14993. };
  14994. /**
  14995. * Remove an externaly attached data from the Engine instance
  14996. * @param key the unique key that identifies the data
  14997. * @return true if the data was successfully removed, false if it doesn't exist
  14998. */
  14999. Engine.prototype.removeExternalData = function (key) {
  15000. if (!this._externalData) {
  15001. this._externalData = new BABYLON.StringDictionary();
  15002. }
  15003. return this._externalData.remove(key);
  15004. };
  15005. Engine.prototype.unbindAllAttributes = function () {
  15006. if (this._mustWipeVertexAttributes) {
  15007. this._mustWipeVertexAttributes = false;
  15008. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  15009. this._gl.disableVertexAttribArray(i);
  15010. this._vertexAttribArraysEnabled[i] = false;
  15011. this._currentBufferPointers[i].active = false;
  15012. }
  15013. return;
  15014. }
  15015. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  15016. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  15017. continue;
  15018. }
  15019. this._gl.disableVertexAttribArray(i);
  15020. this._vertexAttribArraysEnabled[i] = false;
  15021. this._currentBufferPointers[i].active = false;
  15022. }
  15023. };
  15024. Engine.prototype.releaseEffects = function () {
  15025. for (var name in this._compiledEffects) {
  15026. this._deleteProgram(this._compiledEffects[name]._program);
  15027. }
  15028. this._compiledEffects = {};
  15029. };
  15030. // Dispose
  15031. Engine.prototype.dispose = function () {
  15032. this.hideLoadingUI();
  15033. this.stopRenderLoop();
  15034. // Release postProcesses
  15035. while (this.postProcesses.length) {
  15036. this.postProcesses[0].dispose();
  15037. }
  15038. // Empty texture
  15039. if (this._emptyTexture) {
  15040. this._releaseTexture(this._emptyTexture);
  15041. this._emptyTexture = null;
  15042. }
  15043. if (this._emptyCubeTexture) {
  15044. this._releaseTexture(this._emptyCubeTexture);
  15045. this._emptyCubeTexture = null;
  15046. }
  15047. // Rescale PP
  15048. if (this._rescalePostProcess) {
  15049. this._rescalePostProcess.dispose();
  15050. }
  15051. // Release scenes
  15052. while (this.scenes.length) {
  15053. this.scenes[0].dispose();
  15054. }
  15055. // Release audio engine
  15056. if (Engine.audioEngine) {
  15057. Engine.audioEngine.dispose();
  15058. }
  15059. // Release effects
  15060. this.releaseEffects();
  15061. // Unbind
  15062. this.unbindAllAttributes();
  15063. if (this._dummyFramebuffer) {
  15064. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  15065. }
  15066. //WebVR
  15067. this.disableVR();
  15068. // Events
  15069. if (BABYLON.Tools.IsWindowObjectExist()) {
  15070. window.removeEventListener("blur", this._onBlur);
  15071. window.removeEventListener("focus", this._onFocus);
  15072. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  15073. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  15074. if (this._renderingCanvas) {
  15075. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  15076. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  15077. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  15078. if (!this._doNotHandleContextLost) {
  15079. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  15080. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  15081. }
  15082. }
  15083. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  15084. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  15085. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  15086. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  15087. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  15088. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  15089. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  15090. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  15091. if (this._onVrDisplayConnect) {
  15092. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  15093. if (this._onVrDisplayDisconnect) {
  15094. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  15095. }
  15096. if (this._onVrDisplayPresentChange) {
  15097. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  15098. }
  15099. this._onVrDisplayConnect = null;
  15100. this._onVrDisplayDisconnect = null;
  15101. }
  15102. }
  15103. // Remove from Instances
  15104. var index = Engine.Instances.indexOf(this);
  15105. if (index >= 0) {
  15106. Engine.Instances.splice(index, 1);
  15107. }
  15108. this._workingCanvas = null;
  15109. this._workingContext = null;
  15110. this._currentBufferPointers = [];
  15111. this._renderingCanvas = null;
  15112. this._currentProgram = null;
  15113. this._bindedRenderFunction = null;
  15114. this.onResizeObservable.clear();
  15115. this.onCanvasBlurObservable.clear();
  15116. this.onCanvasFocusObservable.clear();
  15117. this.onCanvasPointerOutObservable.clear();
  15118. this.onBeginFrameObservable.clear();
  15119. this.onEndFrameObservable.clear();
  15120. BABYLON.Effect.ResetCache();
  15121. // Abort active requests
  15122. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  15123. var request = _a[_i];
  15124. request.abort();
  15125. }
  15126. };
  15127. // Loading screen
  15128. Engine.prototype.displayLoadingUI = function () {
  15129. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15130. return;
  15131. }
  15132. var loadingScreen = this.loadingScreen;
  15133. if (loadingScreen) {
  15134. loadingScreen.displayLoadingUI();
  15135. }
  15136. };
  15137. Engine.prototype.hideLoadingUI = function () {
  15138. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15139. return;
  15140. }
  15141. var loadingScreen = this.loadingScreen;
  15142. if (loadingScreen) {
  15143. loadingScreen.hideLoadingUI();
  15144. }
  15145. };
  15146. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15147. get: function () {
  15148. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15149. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15150. return this._loadingScreen;
  15151. },
  15152. set: function (loadingScreen) {
  15153. this._loadingScreen = loadingScreen;
  15154. },
  15155. enumerable: true,
  15156. configurable: true
  15157. });
  15158. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15159. set: function (text) {
  15160. this.loadingScreen.loadingUIText = text;
  15161. },
  15162. enumerable: true,
  15163. configurable: true
  15164. });
  15165. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15166. set: function (color) {
  15167. this.loadingScreen.loadingUIBackgroundColor = color;
  15168. },
  15169. enumerable: true,
  15170. configurable: true
  15171. });
  15172. Engine.prototype.attachContextLostEvent = function (callback) {
  15173. if (this._renderingCanvas) {
  15174. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15175. }
  15176. };
  15177. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15178. if (this._renderingCanvas) {
  15179. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15180. }
  15181. };
  15182. Engine.prototype.getVertexShaderSource = function (program) {
  15183. var shaders = this._gl.getAttachedShaders(program);
  15184. if (!shaders) {
  15185. return null;
  15186. }
  15187. return this._gl.getShaderSource(shaders[0]);
  15188. };
  15189. Engine.prototype.getFragmentShaderSource = function (program) {
  15190. var shaders = this._gl.getAttachedShaders(program);
  15191. if (!shaders) {
  15192. return null;
  15193. }
  15194. return this._gl.getShaderSource(shaders[1]);
  15195. };
  15196. Engine.prototype.getError = function () {
  15197. return this._gl.getError();
  15198. };
  15199. // FPS
  15200. Engine.prototype.getFps = function () {
  15201. return this._fps;
  15202. };
  15203. Engine.prototype.getDeltaTime = function () {
  15204. return this._deltaTime;
  15205. };
  15206. Engine.prototype._measureFps = function () {
  15207. this._performanceMonitor.sampleFrame();
  15208. this._fps = this._performanceMonitor.averageFPS;
  15209. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15210. };
  15211. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15212. if (faceIndex === void 0) { faceIndex = -1; }
  15213. var gl = this._gl;
  15214. if (!this._dummyFramebuffer) {
  15215. var dummy = gl.createFramebuffer();
  15216. if (!dummy) {
  15217. throw new Error("Unable to create dummy framebuffer");
  15218. }
  15219. this._dummyFramebuffer = dummy;
  15220. }
  15221. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15222. if (faceIndex > -1) {
  15223. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15224. }
  15225. else {
  15226. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15227. }
  15228. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15229. var buffer;
  15230. switch (readType) {
  15231. case gl.UNSIGNED_BYTE:
  15232. buffer = new Uint8Array(4 * width * height);
  15233. readType = gl.UNSIGNED_BYTE;
  15234. break;
  15235. default:
  15236. buffer = new Float32Array(4 * width * height);
  15237. readType = gl.FLOAT;
  15238. break;
  15239. }
  15240. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15241. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15242. return buffer;
  15243. };
  15244. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15245. if (this._webGLVersion > 1) {
  15246. return this._caps.colorBufferFloat;
  15247. }
  15248. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15249. };
  15250. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15251. if (this._webGLVersion > 1) {
  15252. return this._caps.colorBufferFloat;
  15253. }
  15254. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15255. };
  15256. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15257. Engine.prototype._canRenderToFramebuffer = function (type) {
  15258. var gl = this._gl;
  15259. //clear existing errors
  15260. while (gl.getError() !== gl.NO_ERROR) { }
  15261. var successful = true;
  15262. var texture = gl.createTexture();
  15263. gl.bindTexture(gl.TEXTURE_2D, texture);
  15264. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15265. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15266. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15267. var fb = gl.createFramebuffer();
  15268. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15269. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15270. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15271. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15272. successful = successful && (gl.getError() === gl.NO_ERROR);
  15273. //try render by clearing frame buffer's color buffer
  15274. if (successful) {
  15275. gl.clear(gl.COLOR_BUFFER_BIT);
  15276. successful = successful && (gl.getError() === gl.NO_ERROR);
  15277. }
  15278. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15279. if (successful) {
  15280. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15281. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15282. var readFormat = gl.RGBA;
  15283. var readType = gl.UNSIGNED_BYTE;
  15284. var buffer = new Uint8Array(4);
  15285. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15286. successful = successful && (gl.getError() === gl.NO_ERROR);
  15287. }
  15288. //clean up
  15289. gl.deleteTexture(texture);
  15290. gl.deleteFramebuffer(fb);
  15291. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15292. //clear accumulated errors
  15293. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15294. return successful;
  15295. };
  15296. Engine.prototype._getWebGLTextureType = function (type) {
  15297. if (type === Engine.TEXTURETYPE_FLOAT) {
  15298. return this._gl.FLOAT;
  15299. }
  15300. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15301. // Add Half Float Constant.
  15302. return this._gl.HALF_FLOAT_OES;
  15303. }
  15304. return this._gl.UNSIGNED_BYTE;
  15305. };
  15306. ;
  15307. Engine.prototype._getInternalFormat = function (format) {
  15308. var internalFormat = this._gl.RGBA;
  15309. switch (format) {
  15310. case Engine.TEXTUREFORMAT_ALPHA:
  15311. internalFormat = this._gl.ALPHA;
  15312. break;
  15313. case Engine.TEXTUREFORMAT_LUMINANCE:
  15314. internalFormat = this._gl.LUMINANCE;
  15315. break;
  15316. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15317. internalFormat = this._gl.LUMINANCE_ALPHA;
  15318. break;
  15319. case Engine.TEXTUREFORMAT_RGB:
  15320. case Engine.TEXTUREFORMAT_RGB32F:
  15321. internalFormat = this._gl.RGB;
  15322. break;
  15323. case Engine.TEXTUREFORMAT_RGBA:
  15324. case Engine.TEXTUREFORMAT_RGBA32F:
  15325. internalFormat = this._gl.RGBA;
  15326. break;
  15327. case Engine.TEXTUREFORMAT_R32F:
  15328. internalFormat = this._gl.RED;
  15329. break;
  15330. case Engine.TEXTUREFORMAT_RG32F:
  15331. internalFormat = this._gl.RG;
  15332. break;
  15333. }
  15334. return internalFormat;
  15335. };
  15336. /** @ignore */
  15337. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15338. if (this._webGLVersion === 1) {
  15339. if (format) {
  15340. switch (format) {
  15341. case Engine.TEXTUREFORMAT_LUMINANCE:
  15342. return this._gl.LUMINANCE;
  15343. }
  15344. }
  15345. return this._gl.RGBA;
  15346. }
  15347. if (type === Engine.TEXTURETYPE_FLOAT) {
  15348. if (format) {
  15349. switch (format) {
  15350. case Engine.TEXTUREFORMAT_R32F:
  15351. return this._gl.R32F;
  15352. case Engine.TEXTUREFORMAT_RG32F:
  15353. return this._gl.RG32F;
  15354. case Engine.TEXTUREFORMAT_RGB32F:
  15355. return this._gl.RGB32F;
  15356. }
  15357. }
  15358. return this._gl.RGBA32F;
  15359. }
  15360. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15361. return this._gl.RGBA16F;
  15362. }
  15363. if (format) {
  15364. switch (format) {
  15365. case Engine.TEXTUREFORMAT_LUMINANCE:
  15366. return this._gl.LUMINANCE;
  15367. }
  15368. }
  15369. return this._gl.RGBA;
  15370. };
  15371. ;
  15372. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15373. if (type === Engine.TEXTURETYPE_FLOAT) {
  15374. return this._gl.RGBA32F;
  15375. }
  15376. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15377. return this._gl.RGBA16F;
  15378. }
  15379. return this._gl.RGBA8;
  15380. };
  15381. ;
  15382. Engine.prototype.createQuery = function () {
  15383. return this._gl.createQuery();
  15384. };
  15385. Engine.prototype.deleteQuery = function (query) {
  15386. this._gl.deleteQuery(query);
  15387. return this;
  15388. };
  15389. Engine.prototype.isQueryResultAvailable = function (query) {
  15390. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15391. };
  15392. Engine.prototype.getQueryResult = function (query) {
  15393. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15394. };
  15395. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15396. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15397. this._gl.beginQuery(glAlgorithm, query);
  15398. return this;
  15399. };
  15400. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15401. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15402. this._gl.endQuery(glAlgorithm);
  15403. return this;
  15404. };
  15405. /* Time queries */
  15406. Engine.prototype._createTimeQuery = function () {
  15407. var timerQuery = this._caps.timerQuery;
  15408. if (timerQuery.createQueryEXT) {
  15409. return timerQuery.createQueryEXT();
  15410. }
  15411. return this.createQuery();
  15412. };
  15413. Engine.prototype._deleteTimeQuery = function (query) {
  15414. var timerQuery = this._caps.timerQuery;
  15415. if (timerQuery.deleteQueryEXT) {
  15416. timerQuery.deleteQueryEXT(query);
  15417. return;
  15418. }
  15419. this.deleteQuery(query);
  15420. };
  15421. Engine.prototype._getTimeQueryResult = function (query) {
  15422. var timerQuery = this._caps.timerQuery;
  15423. if (timerQuery.getQueryObjectEXT) {
  15424. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15425. }
  15426. return this.getQueryResult(query);
  15427. };
  15428. Engine.prototype._getTimeQueryAvailability = function (query) {
  15429. var timerQuery = this._caps.timerQuery;
  15430. if (timerQuery.getQueryObjectEXT) {
  15431. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15432. }
  15433. return this.isQueryResultAvailable(query);
  15434. };
  15435. Engine.prototype.startTimeQuery = function () {
  15436. var timerQuery = this._caps.timerQuery;
  15437. if (!timerQuery) {
  15438. return null;
  15439. }
  15440. var token = new BABYLON._TimeToken();
  15441. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15442. if (this._caps.canUseTimestampForTimerQuery) {
  15443. token._startTimeQuery = this._createTimeQuery();
  15444. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15445. }
  15446. else {
  15447. if (this._currentNonTimestampToken) {
  15448. return this._currentNonTimestampToken;
  15449. }
  15450. token._timeElapsedQuery = this._createTimeQuery();
  15451. if (timerQuery.beginQueryEXT) {
  15452. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15453. }
  15454. else {
  15455. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15456. }
  15457. this._currentNonTimestampToken = token;
  15458. }
  15459. return token;
  15460. };
  15461. Engine.prototype.endTimeQuery = function (token) {
  15462. var timerQuery = this._caps.timerQuery;
  15463. if (!timerQuery || !token) {
  15464. return -1;
  15465. }
  15466. if (this._caps.canUseTimestampForTimerQuery) {
  15467. if (!token._startTimeQuery) {
  15468. return -1;
  15469. }
  15470. if (!token._endTimeQuery) {
  15471. token._endTimeQuery = this._createTimeQuery();
  15472. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15473. }
  15474. }
  15475. else if (!token._timeElapsedQueryEnded) {
  15476. if (!token._timeElapsedQuery) {
  15477. return -1;
  15478. }
  15479. if (timerQuery.endQueryEXT) {
  15480. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15481. }
  15482. else {
  15483. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15484. }
  15485. token._timeElapsedQueryEnded = true;
  15486. }
  15487. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15488. var available = false;
  15489. if (token._endTimeQuery) {
  15490. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15491. }
  15492. else if (token._timeElapsedQuery) {
  15493. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15494. }
  15495. if (available && !disjoint) {
  15496. var result = 0;
  15497. if (this._caps.canUseTimestampForTimerQuery) {
  15498. if (!token._startTimeQuery || !token._endTimeQuery) {
  15499. return -1;
  15500. }
  15501. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15502. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15503. result = timeEnd - timeStart;
  15504. this._deleteTimeQuery(token._startTimeQuery);
  15505. this._deleteTimeQuery(token._endTimeQuery);
  15506. token._startTimeQuery = null;
  15507. token._endTimeQuery = null;
  15508. }
  15509. else {
  15510. if (!token._timeElapsedQuery) {
  15511. return -1;
  15512. }
  15513. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15514. this._deleteTimeQuery(token._timeElapsedQuery);
  15515. token._timeElapsedQuery = null;
  15516. token._timeElapsedQueryEnded = false;
  15517. this._currentNonTimestampToken = null;
  15518. }
  15519. return result;
  15520. }
  15521. return -1;
  15522. };
  15523. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15524. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15525. };
  15526. // Transform feedback
  15527. Engine.prototype.createTransformFeedback = function () {
  15528. return this._gl.createTransformFeedback();
  15529. };
  15530. Engine.prototype.deleteTransformFeedback = function (value) {
  15531. this._gl.deleteTransformFeedback(value);
  15532. };
  15533. Engine.prototype.bindTransformFeedback = function (value) {
  15534. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15535. };
  15536. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15537. if (usePoints === void 0) { usePoints = true; }
  15538. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15539. };
  15540. Engine.prototype.endTransformFeedback = function () {
  15541. this._gl.endTransformFeedback();
  15542. };
  15543. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15544. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15545. };
  15546. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15547. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15548. };
  15549. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15550. var _this = this;
  15551. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15552. this._activeRequests.push(request);
  15553. request.onCompleteObservable.add(function (request) {
  15554. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15555. });
  15556. return request;
  15557. };
  15558. /** @ignore */
  15559. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15560. var _this = this;
  15561. return new Promise(function (resolve, reject) {
  15562. _this._loadFile(url, function (data) {
  15563. resolve(data);
  15564. }, undefined, database, useArrayBuffer, function (request, exception) {
  15565. reject(exception);
  15566. });
  15567. });
  15568. };
  15569. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15570. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15571. var onload = function (data) {
  15572. loadedFiles[index] = data;
  15573. loadedFiles._internalCount++;
  15574. if (loadedFiles._internalCount === 6) {
  15575. onfinish(loadedFiles);
  15576. }
  15577. };
  15578. var onerror = function (request, exception) {
  15579. if (onErrorCallBack && request) {
  15580. onErrorCallBack(request.status + " " + request.statusText, exception);
  15581. }
  15582. };
  15583. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15584. };
  15585. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15586. if (onError === void 0) { onError = null; }
  15587. var loadedFiles = [];
  15588. loadedFiles._internalCount = 0;
  15589. for (var index = 0; index < 6; index++) {
  15590. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15591. }
  15592. };
  15593. // Statics
  15594. Engine.isSupported = function () {
  15595. try {
  15596. var tempcanvas = document.createElement("canvas");
  15597. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15598. return gl != null && !!window.WebGLRenderingContext;
  15599. }
  15600. catch (e) {
  15601. return false;
  15602. }
  15603. };
  15604. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15605. Engine.ExceptionList = [
  15606. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15607. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15608. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15609. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15610. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15611. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15612. ];
  15613. Engine.Instances = new Array();
  15614. // Const statics
  15615. Engine._ALPHA_DISABLE = 0;
  15616. Engine._ALPHA_ADD = 1;
  15617. Engine._ALPHA_COMBINE = 2;
  15618. Engine._ALPHA_SUBTRACT = 3;
  15619. Engine._ALPHA_MULTIPLY = 4;
  15620. Engine._ALPHA_MAXIMIZED = 5;
  15621. Engine._ALPHA_ONEONE = 6;
  15622. Engine._ALPHA_PREMULTIPLIED = 7;
  15623. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15624. Engine._ALPHA_INTERPOLATE = 9;
  15625. Engine._ALPHA_SCREENMODE = 10;
  15626. Engine._DELAYLOADSTATE_NONE = 0;
  15627. Engine._DELAYLOADSTATE_LOADED = 1;
  15628. Engine._DELAYLOADSTATE_LOADING = 2;
  15629. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15630. Engine._TEXTUREFORMAT_ALPHA = 0;
  15631. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15632. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15633. Engine._TEXTUREFORMAT_RGB = 4;
  15634. Engine._TEXTUREFORMAT_RGBA = 5;
  15635. Engine._TEXTUREFORMAT_R32F = 6;
  15636. Engine._TEXTUREFORMAT_RG32F = 7;
  15637. Engine._TEXTUREFORMAT_RGB32F = 8;
  15638. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15639. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15640. Engine._TEXTURETYPE_FLOAT = 1;
  15641. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15642. // Depht or Stencil test Constants.
  15643. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15644. 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.
  15645. 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.
  15646. 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.
  15647. 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.
  15648. 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.
  15649. 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.
  15650. 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.
  15651. // Stencil Actions Constants.
  15652. Engine._KEEP = 0x1E00;
  15653. Engine._REPLACE = 0x1E01;
  15654. Engine._INCR = 0x1E02;
  15655. Engine._DECR = 0x1E03;
  15656. Engine._INVERT = 0x150A;
  15657. Engine._INCR_WRAP = 0x8507;
  15658. Engine._DECR_WRAP = 0x8508;
  15659. // Texture rescaling mode
  15660. Engine._SCALEMODE_FLOOR = 1;
  15661. Engine._SCALEMODE_NEAREST = 2;
  15662. Engine._SCALEMODE_CEILING = 3;
  15663. // Updatable statics so stick with vars here
  15664. Engine.CollisionsEpsilon = 0.001;
  15665. Engine.CodeRepository = "src/";
  15666. Engine.ShadersRepository = "src/Shaders/";
  15667. return Engine;
  15668. }());
  15669. BABYLON.Engine = Engine;
  15670. })(BABYLON || (BABYLON = {}));
  15671. //# sourceMappingURL=babylon.engine.js.map
  15672. "use strict";
  15673. var BABYLON;
  15674. (function (BABYLON) {
  15675. /**
  15676. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15677. */
  15678. var Node = /** @class */ (function () {
  15679. /**
  15680. * Creates a new Node
  15681. * @param {string} name - the name and id to be given to this node
  15682. * @param {BABYLON.Scene} the scene this node will be added to
  15683. */
  15684. function Node(name, scene) {
  15685. if (scene === void 0) { scene = null; }
  15686. /**
  15687. * Gets or sets a string used to store user defined state for the node
  15688. */
  15689. this.state = "";
  15690. /**
  15691. * Gets or sets an object used to store user defined information for the node
  15692. */
  15693. this.metadata = null;
  15694. /**
  15695. * Gets or sets a boolean used to define if the node must be serialized
  15696. */
  15697. this.doNotSerialize = false;
  15698. /** @ignore */
  15699. this._isDisposed = false;
  15700. /**
  15701. * Gets a list of {BABYLON.Animation} associated with the node
  15702. */
  15703. this.animations = new Array();
  15704. this._ranges = {};
  15705. this._isEnabled = true;
  15706. this._isReady = true;
  15707. /** @ignore */
  15708. this._currentRenderId = -1;
  15709. this._parentRenderId = -1;
  15710. this._animationPropertiesOverride = null;
  15711. /**
  15712. * An event triggered when the mesh is disposed
  15713. * @type {BABYLON.Observable}
  15714. */
  15715. this.onDisposeObservable = new BABYLON.Observable();
  15716. // Behaviors
  15717. this._behaviors = new Array();
  15718. this.name = name;
  15719. this.id = name;
  15720. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15721. this.uniqueId = this._scene.getUniqueId();
  15722. this._initCache();
  15723. }
  15724. /**
  15725. * Gets a boolean indicating if the node has been disposed
  15726. * @returns true if the node was disposed
  15727. */
  15728. Node.prototype.isDisposed = function () {
  15729. return this._isDisposed;
  15730. };
  15731. Object.defineProperty(Node.prototype, "parent", {
  15732. get: function () {
  15733. return this._parentNode;
  15734. },
  15735. /**
  15736. * Gets or sets the parent of the node
  15737. */
  15738. set: function (parent) {
  15739. if (this._parentNode === parent) {
  15740. return;
  15741. }
  15742. // Remove self from list of children of parent
  15743. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15744. var index = this._parentNode._children.indexOf(this);
  15745. if (index !== -1) {
  15746. this._parentNode._children.splice(index, 1);
  15747. }
  15748. }
  15749. // Store new parent
  15750. this._parentNode = parent;
  15751. // Add as child to new parent
  15752. if (this._parentNode) {
  15753. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15754. this._parentNode._children = new Array();
  15755. }
  15756. this._parentNode._children.push(this);
  15757. }
  15758. },
  15759. enumerable: true,
  15760. configurable: true
  15761. });
  15762. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15763. /**
  15764. * Gets or sets the animation properties override
  15765. */
  15766. get: function () {
  15767. return this._animationPropertiesOverride;
  15768. },
  15769. set: function (value) {
  15770. this._animationPropertiesOverride = value;
  15771. },
  15772. enumerable: true,
  15773. configurable: true
  15774. });
  15775. /**
  15776. * Gets a string idenfifying the name of the class
  15777. * @returns "Node" string
  15778. */
  15779. Node.prototype.getClassName = function () {
  15780. return "Node";
  15781. };
  15782. Object.defineProperty(Node.prototype, "onDispose", {
  15783. /**
  15784. * Sets a callback that will be raised when the node will be disposed
  15785. */
  15786. set: function (callback) {
  15787. if (this._onDisposeObserver) {
  15788. this.onDisposeObservable.remove(this._onDisposeObserver);
  15789. }
  15790. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15791. },
  15792. enumerable: true,
  15793. configurable: true
  15794. });
  15795. /**
  15796. * Gets the scene of the node
  15797. * @returns a {BABYLON.Scene}
  15798. */
  15799. Node.prototype.getScene = function () {
  15800. return this._scene;
  15801. };
  15802. /**
  15803. * Gets the engine of the node
  15804. * @returns a {BABYLON.Engine}
  15805. */
  15806. Node.prototype.getEngine = function () {
  15807. return this._scene.getEngine();
  15808. };
  15809. /**
  15810. * Attach a behavior to the node
  15811. * @see http://doc.babylonjs.com/features/behaviour
  15812. * @param behavior defines the behavior to attach
  15813. * @returns the current Node
  15814. */
  15815. Node.prototype.addBehavior = function (behavior) {
  15816. var _this = this;
  15817. var index = this._behaviors.indexOf(behavior);
  15818. if (index !== -1) {
  15819. return this;
  15820. }
  15821. behavior.init();
  15822. if (this._scene.isLoading) {
  15823. // We defer the attach when the scene will be loaded
  15824. var observer = this._scene.onDataLoadedObservable.add(function () {
  15825. behavior.attach(_this);
  15826. setTimeout(function () {
  15827. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15828. _this._scene.onDataLoadedObservable.remove(observer);
  15829. }, 0);
  15830. });
  15831. }
  15832. else {
  15833. behavior.attach(this);
  15834. }
  15835. this._behaviors.push(behavior);
  15836. return this;
  15837. };
  15838. /**
  15839. * Remove an attached behavior
  15840. * @see http://doc.babylonjs.com/features/behaviour
  15841. * @param behavior defines the behavior to attach
  15842. * @returns the current Node
  15843. */
  15844. Node.prototype.removeBehavior = function (behavior) {
  15845. var index = this._behaviors.indexOf(behavior);
  15846. if (index === -1) {
  15847. return this;
  15848. }
  15849. this._behaviors[index].detach();
  15850. this._behaviors.splice(index, 1);
  15851. return this;
  15852. };
  15853. Object.defineProperty(Node.prototype, "behaviors", {
  15854. /**
  15855. * Gets the list of attached behaviors
  15856. * @see http://doc.babylonjs.com/features/behaviour
  15857. */
  15858. get: function () {
  15859. return this._behaviors;
  15860. },
  15861. enumerable: true,
  15862. configurable: true
  15863. });
  15864. /**
  15865. * Gets an attached behavior by name
  15866. * @param name defines the name of the behavior to look for
  15867. * @see http://doc.babylonjs.com/features/behaviour
  15868. * @returns null if behavior was not found else the requested behavior
  15869. */
  15870. Node.prototype.getBehaviorByName = function (name) {
  15871. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15872. var behavior = _a[_i];
  15873. if (behavior.name === name) {
  15874. return behavior;
  15875. }
  15876. }
  15877. return null;
  15878. };
  15879. /**
  15880. * Returns the world matrix of the node
  15881. * @returns a matrix containing the node's world matrix
  15882. */
  15883. Node.prototype.getWorldMatrix = function () {
  15884. return BABYLON.Matrix.Identity();
  15885. };
  15886. // override it in derived class if you add new variables to the cache
  15887. // and call the parent class method
  15888. /** @ignore */
  15889. Node.prototype._initCache = function () {
  15890. this._cache = {};
  15891. this._cache.parent = undefined;
  15892. };
  15893. /** @ignore */
  15894. Node.prototype.updateCache = function (force) {
  15895. if (!force && this.isSynchronized())
  15896. return;
  15897. this._cache.parent = this.parent;
  15898. this._updateCache();
  15899. };
  15900. // override it in derived class if you add new variables to the cache
  15901. // and call the parent class method if !ignoreParentClass
  15902. /** @ignore */
  15903. Node.prototype._updateCache = function (ignoreParentClass) {
  15904. };
  15905. // override it in derived class if you add new variables to the cache
  15906. /** @ignore */
  15907. Node.prototype._isSynchronized = function () {
  15908. return true;
  15909. };
  15910. /** @ignore */
  15911. Node.prototype._markSyncedWithParent = function () {
  15912. if (this.parent) {
  15913. this._parentRenderId = this.parent._currentRenderId;
  15914. }
  15915. };
  15916. /** @ignore */
  15917. Node.prototype.isSynchronizedWithParent = function () {
  15918. if (!this.parent) {
  15919. return true;
  15920. }
  15921. if (this._parentRenderId !== this.parent._currentRenderId) {
  15922. return false;
  15923. }
  15924. return this.parent.isSynchronized();
  15925. };
  15926. /** @ignore */
  15927. Node.prototype.isSynchronized = function (updateCache) {
  15928. var check = this.hasNewParent();
  15929. check = check || !this.isSynchronizedWithParent();
  15930. check = check || !this._isSynchronized();
  15931. if (updateCache)
  15932. this.updateCache(true);
  15933. return !check;
  15934. };
  15935. /** @ignore */
  15936. Node.prototype.hasNewParent = function (update) {
  15937. if (this._cache.parent === this.parent)
  15938. return false;
  15939. if (update)
  15940. this._cache.parent = this.parent;
  15941. return true;
  15942. };
  15943. /**
  15944. * Is this node ready to be used/rendered
  15945. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15946. * @return true if the node is ready
  15947. */
  15948. Node.prototype.isReady = function (completeCheck) {
  15949. if (completeCheck === void 0) { completeCheck = false; }
  15950. return this._isReady;
  15951. };
  15952. /**
  15953. * Is this node enabled?
  15954. * 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
  15955. * @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
  15956. * @return whether this node (and its parent) is enabled
  15957. * @see setEnabled
  15958. */
  15959. Node.prototype.isEnabled = function (checkAncestors) {
  15960. if (checkAncestors === void 0) { checkAncestors = true; }
  15961. if (checkAncestors === false) {
  15962. return this._isEnabled;
  15963. }
  15964. if (this._isEnabled === false) {
  15965. return false;
  15966. }
  15967. if (this.parent !== undefined && this.parent !== null) {
  15968. return this.parent.isEnabled(checkAncestors);
  15969. }
  15970. return true;
  15971. };
  15972. /**
  15973. * Set the enabled state of this node
  15974. * @param value defines the new enabled state
  15975. * @see isEnabled
  15976. */
  15977. Node.prototype.setEnabled = function (value) {
  15978. this._isEnabled = value;
  15979. };
  15980. /**
  15981. * Is this node a descendant of the given node?
  15982. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15983. * @param ancestor defines the parent node to inspect
  15984. * @see parent
  15985. * @returns a boolean indicating if this node is a descendant of the given node
  15986. */
  15987. Node.prototype.isDescendantOf = function (ancestor) {
  15988. if (this.parent) {
  15989. if (this.parent === ancestor) {
  15990. return true;
  15991. }
  15992. return this.parent.isDescendantOf(ancestor);
  15993. }
  15994. return false;
  15995. };
  15996. /** @ignore */
  15997. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15998. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15999. if (!this._children) {
  16000. return;
  16001. }
  16002. for (var index = 0; index < this._children.length; index++) {
  16003. var item = this._children[index];
  16004. if (!predicate || predicate(item)) {
  16005. results.push(item);
  16006. }
  16007. if (!directDescendantsOnly) {
  16008. item._getDescendants(results, false, predicate);
  16009. }
  16010. }
  16011. };
  16012. /**
  16013. * Will return all nodes that have this node as ascendant
  16014. * @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
  16015. * @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
  16016. * @return all children nodes of all types
  16017. */
  16018. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  16019. var results = new Array();
  16020. this._getDescendants(results, directDescendantsOnly, predicate);
  16021. return results;
  16022. };
  16023. /**
  16024. * Get all child-meshes of this node
  16025. * @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
  16026. * @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
  16027. * @returns an array of {BABYLON.AbstractMesh}
  16028. */
  16029. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  16030. var results = [];
  16031. this._getDescendants(results, directDescendantsOnly, function (node) {
  16032. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  16033. });
  16034. return results;
  16035. };
  16036. /**
  16037. * Get all child-transformNodes of this node
  16038. * @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
  16039. * @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
  16040. * @returns an array of {BABYLON.TransformNode}
  16041. */
  16042. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  16043. var results = [];
  16044. this._getDescendants(results, directDescendantsOnly, function (node) {
  16045. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  16046. });
  16047. return results;
  16048. };
  16049. /**
  16050. * Get all direct children of this node
  16051. * @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
  16052. * @returns an array of {BABYLON.Node}
  16053. */
  16054. Node.prototype.getChildren = function (predicate) {
  16055. return this.getDescendants(true, predicate);
  16056. };
  16057. /** @ignore */
  16058. Node.prototype._setReady = function (state) {
  16059. if (state === this._isReady) {
  16060. return;
  16061. }
  16062. if (!state) {
  16063. this._isReady = false;
  16064. return;
  16065. }
  16066. if (this.onReady) {
  16067. this.onReady(this);
  16068. }
  16069. this._isReady = true;
  16070. };
  16071. /**
  16072. * Get an animation by name
  16073. * @param name defines the name of the animation to look for
  16074. * @returns null if not found else the requested animation
  16075. */
  16076. Node.prototype.getAnimationByName = function (name) {
  16077. for (var i = 0; i < this.animations.length; i++) {
  16078. var animation = this.animations[i];
  16079. if (animation.name === name) {
  16080. return animation;
  16081. }
  16082. }
  16083. return null;
  16084. };
  16085. /**
  16086. * Creates an animation range for this node
  16087. * @param name defines the name of the range
  16088. * @param from defines the starting key
  16089. * @param to defines the end key
  16090. */
  16091. Node.prototype.createAnimationRange = function (name, from, to) {
  16092. // check name not already in use
  16093. if (!this._ranges[name]) {
  16094. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  16095. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16096. if (this.animations[i]) {
  16097. this.animations[i].createRange(name, from, to);
  16098. }
  16099. }
  16100. }
  16101. };
  16102. /**
  16103. * Delete a specific animation range
  16104. * @param name defines the name of the range to delete
  16105. * @param deleteFrames defines if animation frames from the range must be deleted as well
  16106. */
  16107. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  16108. if (deleteFrames === void 0) { deleteFrames = true; }
  16109. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16110. if (this.animations[i]) {
  16111. this.animations[i].deleteRange(name, deleteFrames);
  16112. }
  16113. }
  16114. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  16115. };
  16116. /**
  16117. * Get an animation range by name
  16118. * @param name defines the name of the animation range to look for
  16119. * @returns null if not found else the requested animation range
  16120. */
  16121. Node.prototype.getAnimationRange = function (name) {
  16122. return this._ranges[name];
  16123. };
  16124. /**
  16125. * Will start the animation sequence
  16126. * @param name defines the range frames for animation sequence
  16127. * @param loop defines if the animation should loop (false by default)
  16128. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  16129. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  16130. * @returns the object created for this animation. If range does not exist, it will return null
  16131. */
  16132. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  16133. var range = this.getAnimationRange(name);
  16134. if (!range) {
  16135. return null;
  16136. }
  16137. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  16138. };
  16139. /**
  16140. * Serialize animation ranges into a JSON compatible object
  16141. * @returns serialization object
  16142. */
  16143. Node.prototype.serializeAnimationRanges = function () {
  16144. var serializationRanges = [];
  16145. for (var name in this._ranges) {
  16146. var localRange = this._ranges[name];
  16147. if (!localRange) {
  16148. continue;
  16149. }
  16150. var range = {};
  16151. range.name = name;
  16152. range.from = localRange.from;
  16153. range.to = localRange.to;
  16154. serializationRanges.push(range);
  16155. }
  16156. return serializationRanges;
  16157. };
  16158. /**
  16159. * Computes the world matrix of the node
  16160. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  16161. * @returns the world matrix
  16162. */
  16163. Node.prototype.computeWorldMatrix = function (force) {
  16164. return BABYLON.Matrix.Identity();
  16165. };
  16166. /**
  16167. * Releases resources associated with this node.
  16168. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  16169. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  16170. */
  16171. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16172. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16173. if (!doNotRecurse) {
  16174. var nodes = this.getDescendants(true);
  16175. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16176. var node = nodes_1[_i];
  16177. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16178. }
  16179. }
  16180. else {
  16181. var transformNodes = this.getChildTransformNodes(true);
  16182. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16183. var transformNode = transformNodes_1[_a];
  16184. transformNode.parent = null;
  16185. transformNode.computeWorldMatrix(true);
  16186. }
  16187. }
  16188. this.parent = null;
  16189. // Callback
  16190. this.onDisposeObservable.notifyObservers(this);
  16191. this.onDisposeObservable.clear();
  16192. // Behaviors
  16193. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16194. var behavior = _c[_b];
  16195. behavior.detach();
  16196. }
  16197. this._behaviors = [];
  16198. this._isDisposed = true;
  16199. };
  16200. /**
  16201. * Parse animation range data from a serialization object and store them into a given node
  16202. * @param node defines where to store the animation ranges
  16203. * @param parsedNode defines the serialization object to read data from
  16204. * @param scene defines the hosting scene
  16205. */
  16206. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16207. if (parsedNode.ranges) {
  16208. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16209. var data = parsedNode.ranges[index];
  16210. node.createAnimationRange(data.name, data.from, data.to);
  16211. }
  16212. }
  16213. };
  16214. __decorate([
  16215. BABYLON.serialize()
  16216. ], Node.prototype, "name", void 0);
  16217. __decorate([
  16218. BABYLON.serialize()
  16219. ], Node.prototype, "id", void 0);
  16220. __decorate([
  16221. BABYLON.serialize()
  16222. ], Node.prototype, "uniqueId", void 0);
  16223. __decorate([
  16224. BABYLON.serialize()
  16225. ], Node.prototype, "state", void 0);
  16226. __decorate([
  16227. BABYLON.serialize()
  16228. ], Node.prototype, "metadata", void 0);
  16229. return Node;
  16230. }());
  16231. BABYLON.Node = Node;
  16232. })(BABYLON || (BABYLON = {}));
  16233. //# sourceMappingURL=babylon.node.js.map
  16234. "use strict";
  16235. var BABYLON;
  16236. (function (BABYLON) {
  16237. var BoundingSphere = /** @class */ (function () {
  16238. function BoundingSphere(minimum, maximum) {
  16239. this.minimum = minimum;
  16240. this.maximum = maximum;
  16241. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16242. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16243. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16244. this.radius = distance * 0.5;
  16245. this.centerWorld = BABYLON.Vector3.Zero();
  16246. this._update(BABYLON.Matrix.Identity());
  16247. }
  16248. // Methods
  16249. BoundingSphere.prototype._update = function (world) {
  16250. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16251. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16252. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16253. };
  16254. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16255. for (var i = 0; i < 6; i++) {
  16256. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16257. return false;
  16258. }
  16259. return true;
  16260. };
  16261. BoundingSphere.prototype.intersectsPoint = function (point) {
  16262. var x = this.centerWorld.x - point.x;
  16263. var y = this.centerWorld.y - point.y;
  16264. var z = this.centerWorld.z - point.z;
  16265. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16266. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16267. return false;
  16268. return true;
  16269. };
  16270. // Statics
  16271. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16272. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16273. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16274. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16275. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16276. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16277. return false;
  16278. return true;
  16279. };
  16280. return BoundingSphere;
  16281. }());
  16282. BABYLON.BoundingSphere = BoundingSphere;
  16283. })(BABYLON || (BABYLON = {}));
  16284. //# sourceMappingURL=babylon.boundingSphere.js.map
  16285. "use strict";
  16286. var BABYLON;
  16287. (function (BABYLON) {
  16288. var BoundingBox = /** @class */ (function () {
  16289. function BoundingBox(minimum, maximum) {
  16290. this.minimum = minimum;
  16291. this.maximum = maximum;
  16292. this.vectors = new Array();
  16293. this.vectorsWorld = new Array();
  16294. // Bounding vectors
  16295. this.vectors.push(this.minimum.clone());
  16296. this.vectors.push(this.maximum.clone());
  16297. this.vectors.push(this.minimum.clone());
  16298. this.vectors[2].x = this.maximum.x;
  16299. this.vectors.push(this.minimum.clone());
  16300. this.vectors[3].y = this.maximum.y;
  16301. this.vectors.push(this.minimum.clone());
  16302. this.vectors[4].z = this.maximum.z;
  16303. this.vectors.push(this.maximum.clone());
  16304. this.vectors[5].z = this.minimum.z;
  16305. this.vectors.push(this.maximum.clone());
  16306. this.vectors[6].x = this.minimum.x;
  16307. this.vectors.push(this.maximum.clone());
  16308. this.vectors[7].y = this.minimum.y;
  16309. // OBB
  16310. this.center = this.maximum.add(this.minimum).scale(0.5);
  16311. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16312. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16313. // World
  16314. for (var index = 0; index < this.vectors.length; index++) {
  16315. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16316. }
  16317. this.minimumWorld = BABYLON.Vector3.Zero();
  16318. this.maximumWorld = BABYLON.Vector3.Zero();
  16319. this.centerWorld = BABYLON.Vector3.Zero();
  16320. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16321. this._update(BABYLON.Matrix.Identity());
  16322. }
  16323. // Methods
  16324. BoundingBox.prototype.getWorldMatrix = function () {
  16325. return this._worldMatrix;
  16326. };
  16327. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16328. this._worldMatrix.copyFrom(matrix);
  16329. return this;
  16330. };
  16331. BoundingBox.prototype._update = function (world) {
  16332. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16333. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16334. for (var index = 0; index < this.vectors.length; index++) {
  16335. var v = this.vectorsWorld[index];
  16336. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16337. if (v.x < this.minimumWorld.x)
  16338. this.minimumWorld.x = v.x;
  16339. if (v.y < this.minimumWorld.y)
  16340. this.minimumWorld.y = v.y;
  16341. if (v.z < this.minimumWorld.z)
  16342. this.minimumWorld.z = v.z;
  16343. if (v.x > this.maximumWorld.x)
  16344. this.maximumWorld.x = v.x;
  16345. if (v.y > this.maximumWorld.y)
  16346. this.maximumWorld.y = v.y;
  16347. if (v.z > this.maximumWorld.z)
  16348. this.maximumWorld.z = v.z;
  16349. }
  16350. // Extend
  16351. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16352. this.extendSizeWorld.scaleInPlace(0.5);
  16353. // OBB
  16354. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16355. this.centerWorld.scaleInPlace(0.5);
  16356. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16357. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16358. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16359. this._worldMatrix = world;
  16360. };
  16361. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16362. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16363. };
  16364. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16365. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16366. };
  16367. BoundingBox.prototype.intersectsPoint = function (point) {
  16368. var delta = -BABYLON.Epsilon;
  16369. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16370. return false;
  16371. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16372. return false;
  16373. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16374. return false;
  16375. return true;
  16376. };
  16377. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16378. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16379. };
  16380. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16381. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16382. return false;
  16383. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16384. return false;
  16385. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16386. return false;
  16387. return true;
  16388. };
  16389. // Statics
  16390. BoundingBox.Intersects = function (box0, box1) {
  16391. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16392. return false;
  16393. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16394. return false;
  16395. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16396. return false;
  16397. return true;
  16398. };
  16399. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16400. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16401. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16402. return (num <= (sphereRadius * sphereRadius));
  16403. };
  16404. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16405. for (var p = 0; p < 6; p++) {
  16406. for (var i = 0; i < 8; i++) {
  16407. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16408. return false;
  16409. }
  16410. }
  16411. }
  16412. return true;
  16413. };
  16414. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16415. for (var p = 0; p < 6; p++) {
  16416. var inCount = 8;
  16417. for (var i = 0; i < 8; i++) {
  16418. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16419. --inCount;
  16420. }
  16421. else {
  16422. break;
  16423. }
  16424. }
  16425. if (inCount === 0)
  16426. return false;
  16427. }
  16428. return true;
  16429. };
  16430. return BoundingBox;
  16431. }());
  16432. BABYLON.BoundingBox = BoundingBox;
  16433. })(BABYLON || (BABYLON = {}));
  16434. //# sourceMappingURL=babylon.boundingBox.js.map
  16435. "use strict";
  16436. var BABYLON;
  16437. (function (BABYLON) {
  16438. var computeBoxExtents = function (axis, box) {
  16439. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16440. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16441. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16442. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16443. var r = r0 + r1 + r2;
  16444. return {
  16445. min: p - r,
  16446. max: p + r
  16447. };
  16448. };
  16449. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16450. var axisOverlap = function (axis, box0, box1) {
  16451. var result0 = computeBoxExtents(axis, box0);
  16452. var result1 = computeBoxExtents(axis, box1);
  16453. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16454. };
  16455. var BoundingInfo = /** @class */ (function () {
  16456. function BoundingInfo(minimum, maximum) {
  16457. this.minimum = minimum;
  16458. this.maximum = maximum;
  16459. this._isLocked = false;
  16460. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16461. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16462. }
  16463. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16464. get: function () {
  16465. return this._isLocked;
  16466. },
  16467. set: function (value) {
  16468. this._isLocked = value;
  16469. },
  16470. enumerable: true,
  16471. configurable: true
  16472. });
  16473. // Methods
  16474. BoundingInfo.prototype.update = function (world) {
  16475. if (this._isLocked) {
  16476. return;
  16477. }
  16478. this.boundingBox._update(world);
  16479. this.boundingSphere._update(world);
  16480. };
  16481. /**
  16482. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16483. * @param center New center of the bounding info
  16484. * @param extend New extend of the bounding info
  16485. */
  16486. BoundingInfo.prototype.centerOn = function (center, extend) {
  16487. this.minimum = center.subtract(extend);
  16488. this.maximum = center.add(extend);
  16489. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16490. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16491. return this;
  16492. };
  16493. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16494. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16495. return false;
  16496. return this.boundingBox.isInFrustum(frustumPlanes);
  16497. };
  16498. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16499. /**
  16500. * Gets the world distance between the min and max points of the bounding box
  16501. */
  16502. get: function () {
  16503. var boundingBox = this.boundingBox;
  16504. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16505. return size.length();
  16506. },
  16507. enumerable: true,
  16508. configurable: true
  16509. });
  16510. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16511. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16512. };
  16513. BoundingInfo.prototype._checkCollision = function (collider) {
  16514. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16515. };
  16516. BoundingInfo.prototype.intersectsPoint = function (point) {
  16517. if (!this.boundingSphere.centerWorld) {
  16518. return false;
  16519. }
  16520. if (!this.boundingSphere.intersectsPoint(point)) {
  16521. return false;
  16522. }
  16523. if (!this.boundingBox.intersectsPoint(point)) {
  16524. return false;
  16525. }
  16526. return true;
  16527. };
  16528. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16529. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16530. return false;
  16531. }
  16532. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16533. return false;
  16534. }
  16535. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16536. return false;
  16537. }
  16538. if (!precise) {
  16539. return true;
  16540. }
  16541. var box0 = this.boundingBox;
  16542. var box1 = boundingInfo.boundingBox;
  16543. if (!axisOverlap(box0.directions[0], box0, box1))
  16544. return false;
  16545. if (!axisOverlap(box0.directions[1], box0, box1))
  16546. return false;
  16547. if (!axisOverlap(box0.directions[2], box0, box1))
  16548. return false;
  16549. if (!axisOverlap(box1.directions[0], box0, box1))
  16550. return false;
  16551. if (!axisOverlap(box1.directions[1], box0, box1))
  16552. return false;
  16553. if (!axisOverlap(box1.directions[2], box0, box1))
  16554. return false;
  16555. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16556. return false;
  16557. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16558. return false;
  16559. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16560. return false;
  16561. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16562. return false;
  16563. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16564. return false;
  16565. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16566. return false;
  16567. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16568. return false;
  16569. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16570. return false;
  16571. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16572. return false;
  16573. return true;
  16574. };
  16575. return BoundingInfo;
  16576. }());
  16577. BABYLON.BoundingInfo = BoundingInfo;
  16578. })(BABYLON || (BABYLON = {}));
  16579. //# sourceMappingURL=babylon.boundingInfo.js.map
  16580. "use strict";
  16581. var BABYLON;
  16582. (function (BABYLON) {
  16583. var TransformNode = /** @class */ (function (_super) {
  16584. __extends(TransformNode, _super);
  16585. function TransformNode(name, scene, isPure) {
  16586. if (scene === void 0) { scene = null; }
  16587. if (isPure === void 0) { isPure = true; }
  16588. var _this = _super.call(this, name, scene) || this;
  16589. // Properties
  16590. _this._rotation = BABYLON.Vector3.Zero();
  16591. _this._scaling = BABYLON.Vector3.One();
  16592. _this._isDirty = false;
  16593. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16594. _this.scalingDeterminant = 1;
  16595. _this.infiniteDistance = false;
  16596. _this.position = BABYLON.Vector3.Zero();
  16597. _this._localWorld = BABYLON.Matrix.Zero();
  16598. _this._worldMatrix = BABYLON.Matrix.Zero();
  16599. _this._worldMatrixDeterminant = 0;
  16600. _this._absolutePosition = BABYLON.Vector3.Zero();
  16601. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16602. _this._postMultiplyPivotMatrix = false;
  16603. _this._isWorldMatrixFrozen = false;
  16604. /**
  16605. * An event triggered after the world matrix is updated
  16606. * @type {BABYLON.Observable}
  16607. */
  16608. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16609. _this._nonUniformScaling = false;
  16610. if (isPure) {
  16611. _this.getScene().addTransformNode(_this);
  16612. }
  16613. return _this;
  16614. }
  16615. /**
  16616. * Gets a string idenfifying the name of the class
  16617. * @returns "TransformNode" string
  16618. */
  16619. TransformNode.prototype.getClassName = function () {
  16620. return "TransformNode";
  16621. };
  16622. Object.defineProperty(TransformNode.prototype, "rotation", {
  16623. /**
  16624. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16625. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16626. * Default : (0.0, 0.0, 0.0)
  16627. */
  16628. get: function () {
  16629. return this._rotation;
  16630. },
  16631. set: function (newRotation) {
  16632. this._rotation = newRotation;
  16633. },
  16634. enumerable: true,
  16635. configurable: true
  16636. });
  16637. Object.defineProperty(TransformNode.prototype, "scaling", {
  16638. /**
  16639. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16640. * Default : (1.0, 1.0, 1.0)
  16641. */
  16642. get: function () {
  16643. return this._scaling;
  16644. },
  16645. /**
  16646. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16647. * Default : (1.0, 1.0, 1.0)
  16648. */
  16649. set: function (newScaling) {
  16650. this._scaling = newScaling;
  16651. },
  16652. enumerable: true,
  16653. configurable: true
  16654. });
  16655. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16656. /**
  16657. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16658. * It's null by default.
  16659. * 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)
  16660. */
  16661. get: function () {
  16662. return this._rotationQuaternion;
  16663. },
  16664. set: function (quaternion) {
  16665. this._rotationQuaternion = quaternion;
  16666. //reset the rotation vector.
  16667. if (quaternion && this.rotation.length()) {
  16668. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16669. }
  16670. },
  16671. enumerable: true,
  16672. configurable: true
  16673. });
  16674. /**
  16675. * Returns the latest update of the World matrix
  16676. * Returns a Matrix.
  16677. */
  16678. TransformNode.prototype.getWorldMatrix = function () {
  16679. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16680. this.computeWorldMatrix();
  16681. }
  16682. return this._worldMatrix;
  16683. };
  16684. /**
  16685. * Returns the latest update of the World matrix determinant.
  16686. */
  16687. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16688. return this._worldMatrixDeterminant;
  16689. };
  16690. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16691. /**
  16692. * Returns directly the latest state of the mesh World matrix.
  16693. * A Matrix is returned.
  16694. */
  16695. get: function () {
  16696. return this._worldMatrix;
  16697. },
  16698. enumerable: true,
  16699. configurable: true
  16700. });
  16701. /**
  16702. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16703. * Returns the AbstractMesh.
  16704. */
  16705. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16706. this._poseMatrix.copyFrom(matrix);
  16707. return this;
  16708. };
  16709. /**
  16710. * Returns the mesh Pose matrix.
  16711. * Returned object : Matrix
  16712. */
  16713. TransformNode.prototype.getPoseMatrix = function () {
  16714. return this._poseMatrix;
  16715. };
  16716. TransformNode.prototype._isSynchronized = function () {
  16717. if (this._isDirty) {
  16718. return false;
  16719. }
  16720. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16721. return false;
  16722. if (this._cache.pivotMatrixUpdated) {
  16723. return false;
  16724. }
  16725. if (this.infiniteDistance) {
  16726. return false;
  16727. }
  16728. if (!this._cache.position.equals(this.position))
  16729. return false;
  16730. if (this.rotationQuaternion) {
  16731. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16732. return false;
  16733. }
  16734. if (!this._cache.rotation.equals(this.rotation))
  16735. return false;
  16736. if (!this._cache.scaling.equals(this.scaling))
  16737. return false;
  16738. return true;
  16739. };
  16740. TransformNode.prototype._initCache = function () {
  16741. _super.prototype._initCache.call(this);
  16742. this._cache.localMatrixUpdated = false;
  16743. this._cache.position = BABYLON.Vector3.Zero();
  16744. this._cache.scaling = BABYLON.Vector3.Zero();
  16745. this._cache.rotation = BABYLON.Vector3.Zero();
  16746. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16747. this._cache.billboardMode = -1;
  16748. };
  16749. TransformNode.prototype.markAsDirty = function (property) {
  16750. if (property === "rotation") {
  16751. this.rotationQuaternion = null;
  16752. }
  16753. this._currentRenderId = Number.MAX_VALUE;
  16754. this._isDirty = true;
  16755. return this;
  16756. };
  16757. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16758. /**
  16759. * Returns the current mesh absolute position.
  16760. * Retuns a Vector3.
  16761. */
  16762. get: function () {
  16763. return this._absolutePosition;
  16764. },
  16765. enumerable: true,
  16766. configurable: true
  16767. });
  16768. /**
  16769. * Sets a new matrix to apply before all other transformation
  16770. * @param matrix defines the transform matrix
  16771. * @returns the current TransformNode
  16772. */
  16773. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16774. return this.setPivotMatrix(matrix, false);
  16775. };
  16776. /**
  16777. * Sets a new pivot matrix to the current node
  16778. * @param matrix defines the new pivot matrix to use
  16779. * @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
  16780. * @returns the current TransformNode
  16781. */
  16782. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16783. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16784. this._pivotMatrix = matrix.clone();
  16785. this._cache.pivotMatrixUpdated = true;
  16786. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16787. if (this._postMultiplyPivotMatrix) {
  16788. if (!this._pivotMatrixInverse) {
  16789. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16790. }
  16791. else {
  16792. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16793. }
  16794. }
  16795. return this;
  16796. };
  16797. /**
  16798. * Returns the mesh pivot matrix.
  16799. * Default : Identity.
  16800. * A Matrix is returned.
  16801. */
  16802. TransformNode.prototype.getPivotMatrix = function () {
  16803. return this._pivotMatrix;
  16804. };
  16805. /**
  16806. * Prevents the World matrix to be computed any longer.
  16807. * Returns the AbstractMesh.
  16808. */
  16809. TransformNode.prototype.freezeWorldMatrix = function () {
  16810. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16811. this.computeWorldMatrix(true);
  16812. this._isWorldMatrixFrozen = true;
  16813. return this;
  16814. };
  16815. /**
  16816. * Allows back the World matrix computation.
  16817. * Returns the AbstractMesh.
  16818. */
  16819. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16820. this._isWorldMatrixFrozen = false;
  16821. this.computeWorldMatrix(true);
  16822. return this;
  16823. };
  16824. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16825. /**
  16826. * True if the World matrix has been frozen.
  16827. * Returns a boolean.
  16828. */
  16829. get: function () {
  16830. return this._isWorldMatrixFrozen;
  16831. },
  16832. enumerable: true,
  16833. configurable: true
  16834. });
  16835. /**
  16836. * Retuns the mesh absolute position in the World.
  16837. * Returns a Vector3.
  16838. */
  16839. TransformNode.prototype.getAbsolutePosition = function () {
  16840. this.computeWorldMatrix();
  16841. return this._absolutePosition;
  16842. };
  16843. /**
  16844. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16845. * Returns the AbstractMesh.
  16846. */
  16847. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16848. if (!absolutePosition) {
  16849. return this;
  16850. }
  16851. var absolutePositionX;
  16852. var absolutePositionY;
  16853. var absolutePositionZ;
  16854. if (absolutePosition.x === undefined) {
  16855. if (arguments.length < 3) {
  16856. return this;
  16857. }
  16858. absolutePositionX = arguments[0];
  16859. absolutePositionY = arguments[1];
  16860. absolutePositionZ = arguments[2];
  16861. }
  16862. else {
  16863. absolutePositionX = absolutePosition.x;
  16864. absolutePositionY = absolutePosition.y;
  16865. absolutePositionZ = absolutePosition.z;
  16866. }
  16867. if (this.parent) {
  16868. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16869. invertParentWorldMatrix.invert();
  16870. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16871. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16872. }
  16873. else {
  16874. this.position.x = absolutePositionX;
  16875. this.position.y = absolutePositionY;
  16876. this.position.z = absolutePositionZ;
  16877. }
  16878. return this;
  16879. };
  16880. /**
  16881. * Sets the mesh position in its local space.
  16882. * Returns the AbstractMesh.
  16883. */
  16884. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16885. this.computeWorldMatrix();
  16886. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16887. return this;
  16888. };
  16889. /**
  16890. * Returns the mesh position in the local space from the current World matrix values.
  16891. * Returns a new Vector3.
  16892. */
  16893. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16894. this.computeWorldMatrix();
  16895. var invLocalWorldMatrix = this._localWorld.clone();
  16896. invLocalWorldMatrix.invert();
  16897. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16898. };
  16899. /**
  16900. * Translates the mesh along the passed Vector3 in its local space.
  16901. * Returns the AbstractMesh.
  16902. */
  16903. TransformNode.prototype.locallyTranslate = function (vector3) {
  16904. this.computeWorldMatrix(true);
  16905. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16906. return this;
  16907. };
  16908. /**
  16909. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16910. * @param targetPoint the position (must be in same space as current mesh) to look at
  16911. * @param yawCor optional yaw (y-axis) correction in radians
  16912. * @param pitchCor optional pitch (x-axis) correction in radians
  16913. * @param rollCor optional roll (z-axis) correction in radians
  16914. * @param space the choosen space of the target
  16915. * @returns the TransformNode.
  16916. */
  16917. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16918. if (yawCor === void 0) { yawCor = 0; }
  16919. if (pitchCor === void 0) { pitchCor = 0; }
  16920. if (rollCor === void 0) { rollCor = 0; }
  16921. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16922. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16923. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16924. targetPoint.subtractToRef(pos, dv);
  16925. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16926. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16927. var pitch = Math.atan2(dv.y, len);
  16928. if (this.rotationQuaternion) {
  16929. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16930. }
  16931. else {
  16932. this.rotation.x = pitch + pitchCor;
  16933. this.rotation.y = yaw + yawCor;
  16934. this.rotation.z = rollCor;
  16935. }
  16936. return this;
  16937. };
  16938. /**
  16939. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16940. * This Vector3 is expressed in the World space.
  16941. */
  16942. TransformNode.prototype.getDirection = function (localAxis) {
  16943. var result = BABYLON.Vector3.Zero();
  16944. this.getDirectionToRef(localAxis, result);
  16945. return result;
  16946. };
  16947. /**
  16948. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16949. * localAxis is expressed in the mesh local space.
  16950. * result is computed in the Wordl space from the mesh World matrix.
  16951. * Returns the AbstractMesh.
  16952. */
  16953. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16954. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16955. return this;
  16956. };
  16957. /**
  16958. * Sets a new pivot point to the current node
  16959. * @param point defines the new pivot point to use
  16960. * @param space defines if the point is in world or local space (local by default)
  16961. * @returns the current TransformNode
  16962. */
  16963. TransformNode.prototype.setPivotPoint = function (point, space) {
  16964. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16965. if (this.getScene().getRenderId() == 0) {
  16966. this.computeWorldMatrix(true);
  16967. }
  16968. var wm = this.getWorldMatrix();
  16969. if (space == BABYLON.Space.WORLD) {
  16970. var tmat = BABYLON.Tmp.Matrix[0];
  16971. wm.invertToRef(tmat);
  16972. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16973. }
  16974. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16975. };
  16976. /**
  16977. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16978. */
  16979. TransformNode.prototype.getPivotPoint = function () {
  16980. var point = BABYLON.Vector3.Zero();
  16981. this.getPivotPointToRef(point);
  16982. return point;
  16983. };
  16984. /**
  16985. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16986. * Returns the AbstractMesh.
  16987. */
  16988. TransformNode.prototype.getPivotPointToRef = function (result) {
  16989. result.x = -this._pivotMatrix.m[12];
  16990. result.y = -this._pivotMatrix.m[13];
  16991. result.z = -this._pivotMatrix.m[14];
  16992. return this;
  16993. };
  16994. /**
  16995. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16996. */
  16997. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16998. var point = BABYLON.Vector3.Zero();
  16999. this.getAbsolutePivotPointToRef(point);
  17000. return point;
  17001. };
  17002. /**
  17003. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  17004. * Returns the AbstractMesh.
  17005. */
  17006. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  17007. result.x = this._pivotMatrix.m[12];
  17008. result.y = this._pivotMatrix.m[13];
  17009. result.z = this._pivotMatrix.m[14];
  17010. this.getPivotPointToRef(result);
  17011. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  17012. return this;
  17013. };
  17014. /**
  17015. * Defines the passed node as the parent of the current node.
  17016. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  17017. * Returns the TransformNode.
  17018. */
  17019. TransformNode.prototype.setParent = function (node) {
  17020. if (node === null) {
  17021. var rotation = BABYLON.Tmp.Quaternion[0];
  17022. var position = BABYLON.Tmp.Vector3[0];
  17023. var scale = BABYLON.Tmp.Vector3[1];
  17024. if (this.parent && this.parent.computeWorldMatrix) {
  17025. this.parent.computeWorldMatrix(true);
  17026. }
  17027. this.computeWorldMatrix(true);
  17028. this.getWorldMatrix().decompose(scale, rotation, position);
  17029. if (this.rotationQuaternion) {
  17030. this.rotationQuaternion.copyFrom(rotation);
  17031. }
  17032. else {
  17033. rotation.toEulerAnglesToRef(this.rotation);
  17034. }
  17035. this.scaling.x = scale.x;
  17036. this.scaling.y = scale.y;
  17037. this.scaling.z = scale.z;
  17038. this.position.x = position.x;
  17039. this.position.y = position.y;
  17040. this.position.z = position.z;
  17041. }
  17042. else {
  17043. var rotation = BABYLON.Tmp.Quaternion[0];
  17044. var position = BABYLON.Tmp.Vector3[0];
  17045. var scale = BABYLON.Tmp.Vector3[1];
  17046. var diffMatrix = BABYLON.Tmp.Matrix[0];
  17047. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  17048. this.computeWorldMatrix(true);
  17049. node.computeWorldMatrix(true);
  17050. node.getWorldMatrix().invertToRef(invParentMatrix);
  17051. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  17052. diffMatrix.decompose(scale, rotation, position);
  17053. if (this.rotationQuaternion) {
  17054. this.rotationQuaternion.copyFrom(rotation);
  17055. }
  17056. else {
  17057. rotation.toEulerAnglesToRef(this.rotation);
  17058. }
  17059. this.position.x = position.x;
  17060. this.position.y = position.y;
  17061. this.position.z = position.z;
  17062. this.scaling.x = scale.x;
  17063. this.scaling.y = scale.y;
  17064. this.scaling.z = scale.z;
  17065. }
  17066. this.parent = node;
  17067. return this;
  17068. };
  17069. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  17070. get: function () {
  17071. return this._nonUniformScaling;
  17072. },
  17073. enumerable: true,
  17074. configurable: true
  17075. });
  17076. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  17077. if (this._nonUniformScaling === value) {
  17078. return false;
  17079. }
  17080. this._nonUniformScaling = true;
  17081. return true;
  17082. };
  17083. /**
  17084. * Attach the current TransformNode to another TransformNode associated with a bone
  17085. * @param bone Bone affecting the TransformNode
  17086. * @param affectedTransformNode TransformNode associated with the bone
  17087. */
  17088. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  17089. this._transformToBoneReferal = affectedTransformNode;
  17090. this.parent = bone;
  17091. if (bone.getWorldMatrix().determinant() < 0) {
  17092. this.scalingDeterminant *= -1;
  17093. }
  17094. return this;
  17095. };
  17096. TransformNode.prototype.detachFromBone = function () {
  17097. if (!this.parent) {
  17098. return this;
  17099. }
  17100. if (this.parent.getWorldMatrix().determinant() < 0) {
  17101. this.scalingDeterminant *= -1;
  17102. }
  17103. this._transformToBoneReferal = null;
  17104. this.parent = null;
  17105. return this;
  17106. };
  17107. /**
  17108. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  17109. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17110. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17111. * The passed axis is also normalized.
  17112. * Returns the AbstractMesh.
  17113. */
  17114. TransformNode.prototype.rotate = function (axis, amount, space) {
  17115. axis.normalize();
  17116. if (!this.rotationQuaternion) {
  17117. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17118. this.rotation = BABYLON.Vector3.Zero();
  17119. }
  17120. var rotationQuaternion;
  17121. if (!space || space === BABYLON.Space.LOCAL) {
  17122. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17123. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  17124. }
  17125. else {
  17126. if (this.parent) {
  17127. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17128. invertParentWorldMatrix.invert();
  17129. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  17130. }
  17131. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17132. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17133. }
  17134. return this;
  17135. };
  17136. /**
  17137. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  17138. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17139. * The passed axis is also normalized.
  17140. * Returns the AbstractMesh.
  17141. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  17142. */
  17143. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  17144. axis.normalize();
  17145. if (!this.rotationQuaternion) {
  17146. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17147. this.rotation.copyFromFloats(0, 0, 0);
  17148. }
  17149. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  17150. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  17151. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  17152. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  17153. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  17154. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  17155. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  17156. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  17157. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17158. return this;
  17159. };
  17160. /**
  17161. * Translates the mesh along the axis vector for the passed distance in the given space.
  17162. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17163. * Returns the AbstractMesh.
  17164. */
  17165. TransformNode.prototype.translate = function (axis, distance, space) {
  17166. var displacementVector = axis.scale(distance);
  17167. if (!space || space === BABYLON.Space.LOCAL) {
  17168. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  17169. this.setPositionWithLocalVector(tempV3);
  17170. }
  17171. else {
  17172. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  17173. }
  17174. return this;
  17175. };
  17176. /**
  17177. * Adds a rotation step to the mesh current rotation.
  17178. * x, y, z are Euler angles expressed in radians.
  17179. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17180. * This means this rotation is made in the mesh local space only.
  17181. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17182. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17183. * ```javascript
  17184. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17185. * ```
  17186. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17187. * 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.
  17188. * Returns the AbstractMesh.
  17189. */
  17190. TransformNode.prototype.addRotation = function (x, y, z) {
  17191. var rotationQuaternion;
  17192. if (this.rotationQuaternion) {
  17193. rotationQuaternion = this.rotationQuaternion;
  17194. }
  17195. else {
  17196. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17197. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17198. }
  17199. var accumulation = BABYLON.Tmp.Quaternion[0];
  17200. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17201. rotationQuaternion.multiplyInPlace(accumulation);
  17202. if (!this.rotationQuaternion) {
  17203. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17204. }
  17205. return this;
  17206. };
  17207. /**
  17208. * Computes the mesh World matrix and returns it.
  17209. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17210. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17211. * If the parameter `force`is set to `true`, the actual computation is done.
  17212. * Returns the mesh World Matrix.
  17213. */
  17214. TransformNode.prototype.computeWorldMatrix = function (force) {
  17215. if (this._isWorldMatrixFrozen) {
  17216. return this._worldMatrix;
  17217. }
  17218. if (!force && this.isSynchronized(true)) {
  17219. return this._worldMatrix;
  17220. }
  17221. this._cache.position.copyFrom(this.position);
  17222. this._cache.scaling.copyFrom(this.scaling);
  17223. this._cache.pivotMatrixUpdated = false;
  17224. this._cache.billboardMode = this.billboardMode;
  17225. this._currentRenderId = this.getScene().getRenderId();
  17226. this._isDirty = false;
  17227. // Scaling
  17228. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17229. // Rotation
  17230. //rotate, if quaternion is set and rotation was used
  17231. if (this.rotationQuaternion) {
  17232. var len = this.rotation.length();
  17233. if (len) {
  17234. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17235. this.rotation.copyFromFloats(0, 0, 0);
  17236. }
  17237. }
  17238. if (this.rotationQuaternion) {
  17239. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17240. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17241. }
  17242. else {
  17243. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17244. this._cache.rotation.copyFrom(this.rotation);
  17245. }
  17246. // Translation
  17247. var camera = this.getScene().activeCamera;
  17248. if (this.infiniteDistance && !this.parent && camera) {
  17249. var cameraWorldMatrix = camera.getWorldMatrix();
  17250. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17251. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17252. }
  17253. else {
  17254. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17255. }
  17256. // Composing transformations
  17257. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17258. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17259. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17260. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  17261. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  17262. // Need to decompose each rotation here
  17263. var currentPosition = BABYLON.Tmp.Vector3[3];
  17264. if (this.parent && this.parent.getWorldMatrix) {
  17265. if (this._transformToBoneReferal) {
  17266. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17267. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17268. }
  17269. else {
  17270. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17271. }
  17272. }
  17273. else {
  17274. currentPosition.copyFrom(this.position);
  17275. }
  17276. currentPosition.subtractInPlace(camera.globalPosition);
  17277. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17278. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  17279. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17280. }
  17281. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  17282. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17283. }
  17284. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  17285. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17286. }
  17287. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17288. }
  17289. else {
  17290. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17291. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17292. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17293. }
  17294. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17295. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17296. }
  17297. // Local world
  17298. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17299. // Parent
  17300. if (this.parent && this.parent.getWorldMatrix) {
  17301. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17302. if (this._transformToBoneReferal) {
  17303. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17304. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17305. }
  17306. else {
  17307. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17308. }
  17309. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17310. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17311. this._worldMatrix.copyFrom(this._localWorld);
  17312. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17313. }
  17314. else {
  17315. if (this._transformToBoneReferal) {
  17316. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17317. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17318. }
  17319. else {
  17320. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17321. }
  17322. }
  17323. this._markSyncedWithParent();
  17324. }
  17325. else {
  17326. this._worldMatrix.copyFrom(this._localWorld);
  17327. }
  17328. // Post multiply inverse of pivotMatrix
  17329. if (this._postMultiplyPivotMatrix) {
  17330. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17331. }
  17332. // Normal matrix
  17333. if (this.scaling.isNonUniform) {
  17334. this._updateNonUniformScalingState(true);
  17335. }
  17336. else if (this.parent && this.parent._nonUniformScaling) {
  17337. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17338. }
  17339. else {
  17340. this._updateNonUniformScalingState(false);
  17341. }
  17342. this._afterComputeWorldMatrix();
  17343. // Absolute position
  17344. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17345. // Callbacks
  17346. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17347. if (!this._poseMatrix) {
  17348. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17349. }
  17350. // Cache the determinant
  17351. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17352. return this._worldMatrix;
  17353. };
  17354. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17355. };
  17356. /**
  17357. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17358. * @param func: callback function to add
  17359. *
  17360. * Returns the TransformNode.
  17361. */
  17362. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17363. this.onAfterWorldMatrixUpdateObservable.add(func);
  17364. return this;
  17365. };
  17366. /**
  17367. * Removes a registered callback function.
  17368. * Returns the TransformNode.
  17369. */
  17370. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17371. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17372. return this;
  17373. };
  17374. /**
  17375. * Clone the current transform node
  17376. * Returns the new transform node
  17377. * @param name Name of the new clone
  17378. * @param newParent New parent for the clone
  17379. * @param doNotCloneChildren Do not clone children hierarchy
  17380. */
  17381. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17382. var _this = this;
  17383. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17384. result.name = name;
  17385. result.id = name;
  17386. if (newParent) {
  17387. result.parent = newParent;
  17388. }
  17389. if (!doNotCloneChildren) {
  17390. // Children
  17391. var directDescendants = this.getDescendants(true);
  17392. for (var index = 0; index < directDescendants.length; index++) {
  17393. var child = directDescendants[index];
  17394. if (child.clone) {
  17395. child.clone(name + "." + child.name, result);
  17396. }
  17397. }
  17398. }
  17399. return result;
  17400. };
  17401. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17402. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17403. serializationObject.type = this.getClassName();
  17404. // Parent
  17405. if (this.parent) {
  17406. serializationObject.parentId = this.parent.id;
  17407. }
  17408. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17409. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17410. }
  17411. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17412. serializationObject.isEnabled = this.isEnabled();
  17413. // Parent
  17414. if (this.parent) {
  17415. serializationObject.parentId = this.parent.id;
  17416. }
  17417. return serializationObject;
  17418. };
  17419. // Statics
  17420. /**
  17421. * Returns a new TransformNode object parsed from the source provided.
  17422. * The parameter `parsedMesh` is the source.
  17423. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17424. */
  17425. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17426. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17427. if (BABYLON.Tags) {
  17428. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17429. }
  17430. if (parsedTransformNode.localMatrix) {
  17431. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17432. }
  17433. else if (parsedTransformNode.pivotMatrix) {
  17434. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17435. }
  17436. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17437. // Parent
  17438. if (parsedTransformNode.parentId) {
  17439. transformNode._waitingParentId = parsedTransformNode.parentId;
  17440. }
  17441. return transformNode;
  17442. };
  17443. /**
  17444. * Releases resources associated with this transform node.
  17445. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17446. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17447. */
  17448. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17449. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17450. // Animations
  17451. this.getScene().stopAnimation(this);
  17452. // Remove from scene
  17453. this.getScene().removeTransformNode(this);
  17454. this.onAfterWorldMatrixUpdateObservable.clear();
  17455. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17456. };
  17457. // Statics
  17458. TransformNode.BILLBOARDMODE_NONE = 0;
  17459. TransformNode.BILLBOARDMODE_X = 1;
  17460. TransformNode.BILLBOARDMODE_Y = 2;
  17461. TransformNode.BILLBOARDMODE_Z = 4;
  17462. TransformNode.BILLBOARDMODE_ALL = 7;
  17463. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17464. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17465. __decorate([
  17466. BABYLON.serializeAsVector3()
  17467. ], TransformNode.prototype, "_rotation", void 0);
  17468. __decorate([
  17469. BABYLON.serializeAsQuaternion()
  17470. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17471. __decorate([
  17472. BABYLON.serializeAsVector3()
  17473. ], TransformNode.prototype, "_scaling", void 0);
  17474. __decorate([
  17475. BABYLON.serialize()
  17476. ], TransformNode.prototype, "billboardMode", void 0);
  17477. __decorate([
  17478. BABYLON.serialize()
  17479. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17480. __decorate([
  17481. BABYLON.serialize()
  17482. ], TransformNode.prototype, "infiniteDistance", void 0);
  17483. __decorate([
  17484. BABYLON.serializeAsVector3()
  17485. ], TransformNode.prototype, "position", void 0);
  17486. return TransformNode;
  17487. }(BABYLON.Node));
  17488. BABYLON.TransformNode = TransformNode;
  17489. })(BABYLON || (BABYLON = {}));
  17490. //# sourceMappingURL=babylon.transformNode.js.map
  17491. "use strict";
  17492. var BABYLON;
  17493. (function (BABYLON) {
  17494. var AbstractMesh = /** @class */ (function (_super) {
  17495. __extends(AbstractMesh, _super);
  17496. // Constructor
  17497. function AbstractMesh(name, scene) {
  17498. if (scene === void 0) { scene = null; }
  17499. var _this = _super.call(this, name, scene, false) || this;
  17500. _this._facetNb = 0; // facet number
  17501. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17502. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17503. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17504. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17505. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17506. _this._subDiv = {
  17507. max: 1,
  17508. X: 1,
  17509. Y: 1,
  17510. Z: 1
  17511. };
  17512. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17513. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17514. // Events
  17515. /**
  17516. * An event triggered when this mesh collides with another one
  17517. * @type {BABYLON.Observable}
  17518. */
  17519. _this.onCollideObservable = new BABYLON.Observable();
  17520. /**
  17521. * An event triggered when the collision's position changes
  17522. * @type {BABYLON.Observable}
  17523. */
  17524. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17525. /**
  17526. * An event triggered when material is changed
  17527. * @type {BABYLON.Observable}
  17528. */
  17529. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17530. // Properties
  17531. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17532. /**
  17533. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17534. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17535. * or
  17536. * 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.
  17537. * for more info check WebGl documentations
  17538. */
  17539. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17540. /**
  17541. * 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:
  17542. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17543. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17544. * 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.
  17545. */
  17546. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17547. /**
  17548. * 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.
  17549. * The default value is -1 which means don't break the query and wait till the result.
  17550. */
  17551. _this.occlusionRetryCount = -1;
  17552. _this._occlusionInternalRetryCounter = 0;
  17553. _this._isOccluded = false;
  17554. _this._isOcclusionQueryInProgress = false;
  17555. _this._visibility = 1.0;
  17556. _this.alphaIndex = Number.MAX_VALUE;
  17557. _this.isVisible = true;
  17558. _this.isPickable = true;
  17559. _this.showBoundingBox = false;
  17560. _this.showSubMeshesBoundingBox = false;
  17561. _this.isBlocker = false;
  17562. _this.enablePointerMoveEvents = false;
  17563. _this.renderingGroupId = 0;
  17564. _this._receiveShadows = false;
  17565. _this.renderOutline = false;
  17566. _this.outlineColor = BABYLON.Color3.Red();
  17567. _this.outlineWidth = 0.02;
  17568. _this.renderOverlay = false;
  17569. _this.overlayColor = BABYLON.Color3.Red();
  17570. _this.overlayAlpha = 0.5;
  17571. _this._hasVertexAlpha = false;
  17572. _this._useVertexColors = true;
  17573. _this._computeBonesUsingShaders = true;
  17574. _this._numBoneInfluencers = 4;
  17575. _this._applyFog = true;
  17576. _this.useOctreeForRenderingSelection = true;
  17577. _this.useOctreeForPicking = true;
  17578. _this.useOctreeForCollisions = true;
  17579. _this._layerMask = 0x0FFFFFFF;
  17580. /**
  17581. * True if the mesh must be rendered in any case.
  17582. */
  17583. _this.alwaysSelectAsActiveMesh = false;
  17584. /**
  17585. * This scene's action manager
  17586. * @type {BABYLON.ActionManager}
  17587. */
  17588. _this.actionManager = null;
  17589. // Physics
  17590. _this.physicsImpostor = null;
  17591. // Collisions
  17592. _this._checkCollisions = false;
  17593. _this._collisionMask = -1;
  17594. _this._collisionGroup = -1;
  17595. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17596. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17597. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17598. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17599. // Edges
  17600. _this.edgesWidth = 1;
  17601. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17602. // Cache
  17603. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17604. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17605. _this._renderId = 0;
  17606. _this._intersectionsInProgress = new Array();
  17607. _this._unIndexed = false;
  17608. _this._lightSources = new Array();
  17609. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17610. if (collidedMesh === void 0) { collidedMesh = null; }
  17611. //TODO move this to the collision coordinator!
  17612. if (_this.getScene().workerCollisions)
  17613. newPosition.multiplyInPlace(_this._collider._radius);
  17614. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17615. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17616. _this.position.addInPlace(_this._diffPositionForCollisions);
  17617. }
  17618. if (collidedMesh) {
  17619. _this.onCollideObservable.notifyObservers(collidedMesh);
  17620. }
  17621. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17622. };
  17623. _this.getScene().addMesh(_this);
  17624. _this._resyncLightSources();
  17625. return _this;
  17626. }
  17627. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17628. get: function () {
  17629. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17630. },
  17631. enumerable: true,
  17632. configurable: true
  17633. });
  17634. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17635. get: function () {
  17636. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17637. },
  17638. enumerable: true,
  17639. configurable: true
  17640. });
  17641. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17642. get: function () {
  17643. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17644. },
  17645. enumerable: true,
  17646. configurable: true
  17647. });
  17648. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17649. get: function () {
  17650. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17651. },
  17652. enumerable: true,
  17653. configurable: true
  17654. });
  17655. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17656. get: function () {
  17657. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17658. },
  17659. enumerable: true,
  17660. configurable: true
  17661. });
  17662. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17663. /**
  17664. * Read-only : the number of facets in the mesh
  17665. */
  17666. get: function () {
  17667. return this._facetNb;
  17668. },
  17669. enumerable: true,
  17670. configurable: true
  17671. });
  17672. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17673. /**
  17674. * The number (integer) of subdivisions per axis in the partioning space
  17675. */
  17676. get: function () {
  17677. return this._partitioningSubdivisions;
  17678. },
  17679. set: function (nb) {
  17680. this._partitioningSubdivisions = nb;
  17681. },
  17682. enumerable: true,
  17683. configurable: true
  17684. });
  17685. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17686. /**
  17687. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17688. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17689. */
  17690. get: function () {
  17691. return this._partitioningBBoxRatio;
  17692. },
  17693. set: function (ratio) {
  17694. this._partitioningBBoxRatio = ratio;
  17695. },
  17696. enumerable: true,
  17697. configurable: true
  17698. });
  17699. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17700. /**
  17701. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17702. * Works only for updatable meshes.
  17703. * Doesn't work with multi-materials.
  17704. */
  17705. get: function () {
  17706. return this._facetDepthSort;
  17707. },
  17708. set: function (sort) {
  17709. this._facetDepthSort = sort;
  17710. },
  17711. enumerable: true,
  17712. configurable: true
  17713. });
  17714. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17715. /**
  17716. * The location (Vector3) where the facet depth sort must be computed from.
  17717. * By default, the active camera position.
  17718. * Used only when facet depth sort is enabled.
  17719. */
  17720. get: function () {
  17721. return this._facetDepthSortFrom;
  17722. },
  17723. set: function (location) {
  17724. this._facetDepthSortFrom = location;
  17725. },
  17726. enumerable: true,
  17727. configurable: true
  17728. });
  17729. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17730. /**
  17731. * Read-only boolean : is the feature facetData enabled ?
  17732. */
  17733. get: function () {
  17734. return this._facetDataEnabled;
  17735. },
  17736. enumerable: true,
  17737. configurable: true
  17738. });
  17739. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17740. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17741. return false;
  17742. }
  17743. this._markSubMeshesAsMiscDirty();
  17744. return true;
  17745. };
  17746. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17747. set: function (callback) {
  17748. if (this._onCollideObserver) {
  17749. this.onCollideObservable.remove(this._onCollideObserver);
  17750. }
  17751. this._onCollideObserver = this.onCollideObservable.add(callback);
  17752. },
  17753. enumerable: true,
  17754. configurable: true
  17755. });
  17756. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17757. set: function (callback) {
  17758. if (this._onCollisionPositionChangeObserver) {
  17759. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17760. }
  17761. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17762. },
  17763. enumerable: true,
  17764. configurable: true
  17765. });
  17766. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17767. /**
  17768. * Property isOccluded : Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not.
  17769. */
  17770. get: function () {
  17771. return this._isOccluded;
  17772. },
  17773. set: function (value) {
  17774. this._isOccluded = value;
  17775. },
  17776. enumerable: true,
  17777. configurable: true
  17778. });
  17779. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17780. /**
  17781. * Flag to check the progress status of the query
  17782. */
  17783. get: function () {
  17784. return this._isOcclusionQueryInProgress;
  17785. },
  17786. enumerable: true,
  17787. configurable: true
  17788. });
  17789. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17790. /**
  17791. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17792. */
  17793. get: function () {
  17794. return this._visibility;
  17795. },
  17796. /**
  17797. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17798. */
  17799. set: function (value) {
  17800. if (this._visibility === value) {
  17801. return;
  17802. }
  17803. this._visibility = value;
  17804. this._markSubMeshesAsMiscDirty();
  17805. },
  17806. enumerable: true,
  17807. configurable: true
  17808. });
  17809. Object.defineProperty(AbstractMesh.prototype, "material", {
  17810. get: function () {
  17811. return this._material;
  17812. },
  17813. set: function (value) {
  17814. if (this._material === value) {
  17815. return;
  17816. }
  17817. this._material = value;
  17818. if (this.onMaterialChangedObservable.hasObservers) {
  17819. this.onMaterialChangedObservable.notifyObservers(this);
  17820. }
  17821. if (!this.subMeshes) {
  17822. return;
  17823. }
  17824. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17825. var subMesh = _a[_i];
  17826. subMesh.setEffect(null);
  17827. }
  17828. },
  17829. enumerable: true,
  17830. configurable: true
  17831. });
  17832. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17833. get: function () {
  17834. return this._receiveShadows;
  17835. },
  17836. set: function (value) {
  17837. if (this._receiveShadows === value) {
  17838. return;
  17839. }
  17840. this._receiveShadows = value;
  17841. this._markSubMeshesAsLightDirty();
  17842. },
  17843. enumerable: true,
  17844. configurable: true
  17845. });
  17846. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17847. get: function () {
  17848. return this._hasVertexAlpha;
  17849. },
  17850. set: function (value) {
  17851. if (this._hasVertexAlpha === value) {
  17852. return;
  17853. }
  17854. this._hasVertexAlpha = value;
  17855. this._markSubMeshesAsAttributesDirty();
  17856. this._markSubMeshesAsMiscDirty();
  17857. },
  17858. enumerable: true,
  17859. configurable: true
  17860. });
  17861. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17862. get: function () {
  17863. return this._useVertexColors;
  17864. },
  17865. set: function (value) {
  17866. if (this._useVertexColors === value) {
  17867. return;
  17868. }
  17869. this._useVertexColors = value;
  17870. this._markSubMeshesAsAttributesDirty();
  17871. },
  17872. enumerable: true,
  17873. configurable: true
  17874. });
  17875. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17876. get: function () {
  17877. return this._computeBonesUsingShaders;
  17878. },
  17879. set: function (value) {
  17880. if (this._computeBonesUsingShaders === value) {
  17881. return;
  17882. }
  17883. this._computeBonesUsingShaders = value;
  17884. this._markSubMeshesAsAttributesDirty();
  17885. },
  17886. enumerable: true,
  17887. configurable: true
  17888. });
  17889. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17890. get: function () {
  17891. return this._numBoneInfluencers;
  17892. },
  17893. set: function (value) {
  17894. if (this._numBoneInfluencers === value) {
  17895. return;
  17896. }
  17897. this._numBoneInfluencers = value;
  17898. this._markSubMeshesAsAttributesDirty();
  17899. },
  17900. enumerable: true,
  17901. configurable: true
  17902. });
  17903. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17904. get: function () {
  17905. return this._applyFog;
  17906. },
  17907. set: function (value) {
  17908. if (this._applyFog === value) {
  17909. return;
  17910. }
  17911. this._applyFog = value;
  17912. this._markSubMeshesAsMiscDirty();
  17913. },
  17914. enumerable: true,
  17915. configurable: true
  17916. });
  17917. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17918. get: function () {
  17919. return this._layerMask;
  17920. },
  17921. set: function (value) {
  17922. if (value === this._layerMask) {
  17923. return;
  17924. }
  17925. this._layerMask = value;
  17926. this._resyncLightSources();
  17927. },
  17928. enumerable: true,
  17929. configurable: true
  17930. });
  17931. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17932. get: function () {
  17933. return this._collisionMask;
  17934. },
  17935. set: function (mask) {
  17936. this._collisionMask = !isNaN(mask) ? mask : -1;
  17937. },
  17938. enumerable: true,
  17939. configurable: true
  17940. });
  17941. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17942. get: function () {
  17943. return this._collisionGroup;
  17944. },
  17945. set: function (mask) {
  17946. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17947. },
  17948. enumerable: true,
  17949. configurable: true
  17950. });
  17951. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17952. get: function () {
  17953. return null;
  17954. },
  17955. enumerable: true,
  17956. configurable: true
  17957. });
  17958. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17959. get: function () {
  17960. return this._skeleton;
  17961. },
  17962. set: function (value) {
  17963. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17964. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17965. }
  17966. if (value && value.needInitialSkinMatrix) {
  17967. value._registerMeshWithPoseMatrix(this);
  17968. }
  17969. this._skeleton = value;
  17970. if (!this._skeleton) {
  17971. this._bonesTransformMatrices = null;
  17972. }
  17973. this._markSubMeshesAsAttributesDirty();
  17974. },
  17975. enumerable: true,
  17976. configurable: true
  17977. });
  17978. /**
  17979. * Returns the string "AbstractMesh"
  17980. */
  17981. AbstractMesh.prototype.getClassName = function () {
  17982. return "AbstractMesh";
  17983. };
  17984. /**
  17985. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17986. */
  17987. AbstractMesh.prototype.toString = function (fullDetails) {
  17988. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17989. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17990. if (this._skeleton) {
  17991. ret += ", skeleton: " + this._skeleton.name;
  17992. }
  17993. if (fullDetails) {
  17994. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17995. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17996. }
  17997. return ret;
  17998. };
  17999. AbstractMesh.prototype._rebuild = function () {
  18000. if (this._occlusionQuery) {
  18001. this._occlusionQuery = null;
  18002. }
  18003. if (this._edgesRenderer) {
  18004. this._edgesRenderer._rebuild();
  18005. }
  18006. if (!this.subMeshes) {
  18007. return;
  18008. }
  18009. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18010. var subMesh = _a[_i];
  18011. subMesh._rebuild();
  18012. }
  18013. };
  18014. AbstractMesh.prototype._resyncLightSources = function () {
  18015. this._lightSources.length = 0;
  18016. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  18017. var light = _a[_i];
  18018. if (!light.isEnabled()) {
  18019. continue;
  18020. }
  18021. if (light.canAffectMesh(this)) {
  18022. this._lightSources.push(light);
  18023. }
  18024. }
  18025. this._markSubMeshesAsLightDirty();
  18026. };
  18027. AbstractMesh.prototype._resyncLighSource = function (light) {
  18028. var isIn = light.isEnabled() && light.canAffectMesh(this);
  18029. var index = this._lightSources.indexOf(light);
  18030. if (index === -1) {
  18031. if (!isIn) {
  18032. return;
  18033. }
  18034. this._lightSources.push(light);
  18035. }
  18036. else {
  18037. if (isIn) {
  18038. return;
  18039. }
  18040. this._lightSources.splice(index, 1);
  18041. }
  18042. this._markSubMeshesAsLightDirty();
  18043. };
  18044. AbstractMesh.prototype._removeLightSource = function (light) {
  18045. var index = this._lightSources.indexOf(light);
  18046. if (index === -1) {
  18047. return;
  18048. }
  18049. this._lightSources.splice(index, 1);
  18050. this._markSubMeshesAsLightDirty();
  18051. };
  18052. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  18053. if (!this.subMeshes) {
  18054. return;
  18055. }
  18056. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18057. var subMesh = _a[_i];
  18058. if (subMesh._materialDefines) {
  18059. func(subMesh._materialDefines);
  18060. }
  18061. }
  18062. };
  18063. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  18064. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  18065. };
  18066. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  18067. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  18068. };
  18069. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  18070. if (!this.subMeshes) {
  18071. return;
  18072. }
  18073. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18074. var subMesh = _a[_i];
  18075. var material = subMesh.getMaterial();
  18076. if (material) {
  18077. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  18078. }
  18079. }
  18080. };
  18081. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  18082. /**
  18083. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18084. * Default : (1.0, 1.0, 1.0)
  18085. */
  18086. get: function () {
  18087. return this._scaling;
  18088. },
  18089. /**
  18090. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18091. * Default : (1.0, 1.0, 1.0)
  18092. */
  18093. set: function (newScaling) {
  18094. this._scaling = newScaling;
  18095. if (this.physicsImpostor) {
  18096. this.physicsImpostor.forceUpdate();
  18097. }
  18098. },
  18099. enumerable: true,
  18100. configurable: true
  18101. });
  18102. // Methods
  18103. /**
  18104. * Disables the mesh edger rendering mode.
  18105. * Returns the AbstractMesh.
  18106. */
  18107. AbstractMesh.prototype.disableEdgesRendering = function () {
  18108. if (this._edgesRenderer) {
  18109. this._edgesRenderer.dispose();
  18110. this._edgesRenderer = null;
  18111. }
  18112. return this;
  18113. };
  18114. /**
  18115. * Enables the edge rendering mode on the mesh.
  18116. * This mode makes the mesh edges visible.
  18117. * Returns the AbstractMesh.
  18118. */
  18119. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  18120. if (epsilon === void 0) { epsilon = 0.95; }
  18121. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  18122. this.disableEdgesRendering();
  18123. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  18124. return this;
  18125. };
  18126. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  18127. /**
  18128. * Returns true if the mesh is blocked. Used by the class Mesh.
  18129. * Returns the boolean `false` by default.
  18130. */
  18131. get: function () {
  18132. return false;
  18133. },
  18134. enumerable: true,
  18135. configurable: true
  18136. });
  18137. /**
  18138. * Returns the mesh itself by default, used by the class Mesh.
  18139. * Returned type : AbstractMesh
  18140. */
  18141. AbstractMesh.prototype.getLOD = function (camera) {
  18142. return this;
  18143. };
  18144. /**
  18145. * Returns 0 by default, used by the class Mesh.
  18146. * Returns an integer.
  18147. */
  18148. AbstractMesh.prototype.getTotalVertices = function () {
  18149. return 0;
  18150. };
  18151. /**
  18152. * Returns null by default, used by the class Mesh.
  18153. * Returned type : integer array
  18154. */
  18155. AbstractMesh.prototype.getIndices = function () {
  18156. return null;
  18157. };
  18158. /**
  18159. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  18160. * Returned type : float array or Float32Array
  18161. */
  18162. AbstractMesh.prototype.getVerticesData = function (kind) {
  18163. return null;
  18164. };
  18165. /**
  18166. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18167. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18168. * The `data` are either a numeric array either a Float32Array.
  18169. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18170. * 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).
  18171. * Note that a new underlying VertexBuffer object is created each call.
  18172. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18173. *
  18174. * Possible `kind` values :
  18175. * - BABYLON.VertexBuffer.PositionKind
  18176. * - BABYLON.VertexBuffer.UVKind
  18177. * - BABYLON.VertexBuffer.UV2Kind
  18178. * - BABYLON.VertexBuffer.UV3Kind
  18179. * - BABYLON.VertexBuffer.UV4Kind
  18180. * - BABYLON.VertexBuffer.UV5Kind
  18181. * - BABYLON.VertexBuffer.UV6Kind
  18182. * - BABYLON.VertexBuffer.ColorKind
  18183. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18184. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18185. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18186. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18187. *
  18188. * Returns the Mesh.
  18189. */
  18190. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18191. return this;
  18192. };
  18193. /**
  18194. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18195. * If the mesh has no geometry, it is simply returned as it is.
  18196. * The `data` are either a numeric array either a Float32Array.
  18197. * No new underlying VertexBuffer object is created.
  18198. * 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.
  18199. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18200. *
  18201. * Possible `kind` values :
  18202. * - BABYLON.VertexBuffer.PositionKind
  18203. * - BABYLON.VertexBuffer.UVKind
  18204. * - BABYLON.VertexBuffer.UV2Kind
  18205. * - BABYLON.VertexBuffer.UV3Kind
  18206. * - BABYLON.VertexBuffer.UV4Kind
  18207. * - BABYLON.VertexBuffer.UV5Kind
  18208. * - BABYLON.VertexBuffer.UV6Kind
  18209. * - BABYLON.VertexBuffer.ColorKind
  18210. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18211. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18212. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18213. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18214. *
  18215. * Returns the Mesh.
  18216. */
  18217. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18218. return this;
  18219. };
  18220. /**
  18221. * Sets the mesh indices.
  18222. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18223. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18224. * This method creates a new index buffer each call.
  18225. * Returns the Mesh.
  18226. */
  18227. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18228. return this;
  18229. };
  18230. /** Returns false by default, used by the class Mesh.
  18231. * Returns a boolean
  18232. */
  18233. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18234. return false;
  18235. };
  18236. /**
  18237. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18238. * Returns a BoundingInfo
  18239. */
  18240. AbstractMesh.prototype.getBoundingInfo = function () {
  18241. if (this._masterMesh) {
  18242. return this._masterMesh.getBoundingInfo();
  18243. }
  18244. if (!this._boundingInfo) {
  18245. // this._boundingInfo is being created here
  18246. this._updateBoundingInfo();
  18247. }
  18248. // cannot be null.
  18249. return this._boundingInfo;
  18250. };
  18251. /**
  18252. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18253. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18254. */
  18255. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18256. if (includeDescendants === void 0) { includeDescendants = true; }
  18257. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18258. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18259. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18260. if (maxDimension === 0) {
  18261. return this;
  18262. }
  18263. var scale = 1 / maxDimension;
  18264. this.scaling.scaleInPlace(scale);
  18265. return this;
  18266. };
  18267. /**
  18268. * Sets a mesh new object BoundingInfo.
  18269. * Returns the AbstractMesh.
  18270. */
  18271. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18272. this._boundingInfo = boundingInfo;
  18273. return this;
  18274. };
  18275. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18276. get: function () {
  18277. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18278. },
  18279. enumerable: true,
  18280. configurable: true
  18281. });
  18282. AbstractMesh.prototype._preActivate = function () {
  18283. };
  18284. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18285. };
  18286. AbstractMesh.prototype._activate = function (renderId) {
  18287. this._renderId = renderId;
  18288. };
  18289. /**
  18290. * Returns the latest update of the World matrix
  18291. * Returns a Matrix.
  18292. */
  18293. AbstractMesh.prototype.getWorldMatrix = function () {
  18294. if (this._masterMesh) {
  18295. return this._masterMesh.getWorldMatrix();
  18296. }
  18297. return _super.prototype.getWorldMatrix.call(this);
  18298. };
  18299. /**
  18300. * Returns the latest update of the World matrix determinant.
  18301. */
  18302. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18303. if (this._masterMesh) {
  18304. return this._masterMesh._getWorldMatrixDeterminant();
  18305. }
  18306. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18307. };
  18308. // ================================== Point of View Movement =================================
  18309. /**
  18310. * Perform relative position change from the point of view of behind the front of the mesh.
  18311. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18312. * Supports definition of mesh facing forward or backward.
  18313. * @param {number} amountRight
  18314. * @param {number} amountUp
  18315. * @param {number} amountForward
  18316. *
  18317. * Returns the AbstractMesh.
  18318. */
  18319. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18320. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18321. return this;
  18322. };
  18323. /**
  18324. * Calculate relative position change from the point of view of behind the front of the mesh.
  18325. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18326. * Supports definition of mesh facing forward or backward.
  18327. * @param {number} amountRight
  18328. * @param {number} amountUp
  18329. * @param {number} amountForward
  18330. *
  18331. * Returns a new Vector3.
  18332. */
  18333. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18334. var rotMatrix = new BABYLON.Matrix();
  18335. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18336. rotQuaternion.toRotationMatrix(rotMatrix);
  18337. var translationDelta = BABYLON.Vector3.Zero();
  18338. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18339. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18340. return translationDelta;
  18341. };
  18342. // ================================== Point of View Rotation =================================
  18343. /**
  18344. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18345. * Supports definition of mesh facing forward or backward.
  18346. * @param {number} flipBack
  18347. * @param {number} twirlClockwise
  18348. * @param {number} tiltRight
  18349. *
  18350. * Returns the AbstractMesh.
  18351. */
  18352. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18353. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18354. return this;
  18355. };
  18356. /**
  18357. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18358. * Supports definition of mesh facing forward or backward.
  18359. * @param {number} flipBack
  18360. * @param {number} twirlClockwise
  18361. * @param {number} tiltRight
  18362. *
  18363. * Returns a new Vector3.
  18364. */
  18365. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18366. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18367. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18368. };
  18369. /**
  18370. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18371. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18372. */
  18373. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18374. if (includeDescendants === void 0) { includeDescendants = true; }
  18375. this.computeWorldMatrix(true);
  18376. var min;
  18377. var max;
  18378. var boundingInfo = this.getBoundingInfo();
  18379. if (!this.subMeshes) {
  18380. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18381. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18382. }
  18383. else {
  18384. min = boundingInfo.boundingBox.minimumWorld;
  18385. max = boundingInfo.boundingBox.maximumWorld;
  18386. }
  18387. if (includeDescendants) {
  18388. var descendants = this.getDescendants(false);
  18389. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18390. var descendant = descendants_1[_i];
  18391. var childMesh = descendant;
  18392. childMesh.computeWorldMatrix(true);
  18393. //make sure we have the needed params to get mix and max
  18394. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18395. continue;
  18396. }
  18397. var childBoundingInfo = childMesh.getBoundingInfo();
  18398. var boundingBox = childBoundingInfo.boundingBox;
  18399. var minBox = boundingBox.minimumWorld;
  18400. var maxBox = boundingBox.maximumWorld;
  18401. BABYLON.Tools.CheckExtends(minBox, min, max);
  18402. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18403. }
  18404. }
  18405. return {
  18406. min: min,
  18407. max: max
  18408. };
  18409. };
  18410. /**
  18411. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18412. * Returns the AbstractMesh.
  18413. */
  18414. AbstractMesh.prototype._updateBoundingInfo = function () {
  18415. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18416. this._boundingInfo.update(this.worldMatrixFromCache);
  18417. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18418. return this;
  18419. };
  18420. /**
  18421. * Update a mesh's children BoundingInfo objects only.
  18422. * Returns the AbstractMesh.
  18423. */
  18424. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18425. if (!this.subMeshes) {
  18426. return this;
  18427. }
  18428. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18429. var subMesh = this.subMeshes[subIndex];
  18430. if (!subMesh.IsGlobal) {
  18431. subMesh.updateBoundingInfo(matrix);
  18432. }
  18433. }
  18434. return this;
  18435. };
  18436. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18437. // Bounding info
  18438. this._updateBoundingInfo();
  18439. };
  18440. /**
  18441. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18442. * A mesh is in the frustum if its bounding box intersects the frustum.
  18443. * Boolean returned.
  18444. */
  18445. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18446. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18447. };
  18448. /**
  18449. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18450. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18451. * Boolean returned.
  18452. */
  18453. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18454. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18455. ;
  18456. };
  18457. /**
  18458. * True if the mesh intersects another mesh or a SolidParticle object.
  18459. * 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)
  18460. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18461. * Returns a boolean.
  18462. */
  18463. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18464. if (precise === void 0) { precise = false; }
  18465. if (!this._boundingInfo || !mesh._boundingInfo) {
  18466. return false;
  18467. }
  18468. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18469. return true;
  18470. }
  18471. if (includeDescendants) {
  18472. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18473. var child = _a[_i];
  18474. if (child.intersectsMesh(mesh, precise, true)) {
  18475. return true;
  18476. }
  18477. }
  18478. }
  18479. return false;
  18480. };
  18481. /**
  18482. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18483. * Returns a boolean.
  18484. */
  18485. AbstractMesh.prototype.intersectsPoint = function (point) {
  18486. if (!this._boundingInfo) {
  18487. return false;
  18488. }
  18489. return this._boundingInfo.intersectsPoint(point);
  18490. };
  18491. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18492. return this.physicsImpostor;
  18493. };
  18494. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18495. if (camera === void 0) { camera = null; }
  18496. if (!camera) {
  18497. camera = this.getScene().activeCamera;
  18498. }
  18499. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18500. };
  18501. /**
  18502. * Returns the distance from the mesh to the active camera.
  18503. * Returns a float.
  18504. */
  18505. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18506. if (camera === void 0) { camera = null; }
  18507. if (!camera) {
  18508. camera = this.getScene().activeCamera;
  18509. }
  18510. return this.absolutePosition.subtract(camera.position).length();
  18511. };
  18512. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18513. if (!this.physicsImpostor) {
  18514. return this;
  18515. }
  18516. this.physicsImpostor.applyImpulse(force, contactPoint);
  18517. return this;
  18518. };
  18519. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18520. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18521. return this;
  18522. }
  18523. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18524. mainPivot: pivot1,
  18525. connectedPivot: pivot2,
  18526. nativeParams: options
  18527. });
  18528. return this;
  18529. };
  18530. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18531. // Collisions
  18532. /**
  18533. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18534. * Default `false`.
  18535. */
  18536. get: function () {
  18537. return this._checkCollisions;
  18538. },
  18539. set: function (collisionEnabled) {
  18540. this._checkCollisions = collisionEnabled;
  18541. if (this.getScene().workerCollisions) {
  18542. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18543. }
  18544. },
  18545. enumerable: true,
  18546. configurable: true
  18547. });
  18548. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18549. /**
  18550. * Gets Collider object used to compute collisions (not physics)
  18551. */
  18552. get: function () {
  18553. return this._collider;
  18554. },
  18555. enumerable: true,
  18556. configurable: true
  18557. });
  18558. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18559. var globalPosition = this.getAbsolutePosition();
  18560. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18561. if (!this._collider) {
  18562. this._collider = new BABYLON.Collider();
  18563. }
  18564. this._collider._radius = this.ellipsoid;
  18565. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18566. return this;
  18567. };
  18568. // Submeshes octree
  18569. /**
  18570. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18571. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18572. * Returns an Octree of submeshes.
  18573. */
  18574. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18575. if (maxCapacity === void 0) { maxCapacity = 64; }
  18576. if (maxDepth === void 0) { maxDepth = 2; }
  18577. if (!this._submeshesOctree) {
  18578. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18579. }
  18580. this.computeWorldMatrix(true);
  18581. var boundingInfo = this.getBoundingInfo();
  18582. // Update octree
  18583. var bbox = boundingInfo.boundingBox;
  18584. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18585. return this._submeshesOctree;
  18586. };
  18587. // Collisions
  18588. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18589. this._generatePointsArray();
  18590. if (!this._positions) {
  18591. return this;
  18592. }
  18593. // Transformation
  18594. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18595. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18596. subMesh._lastColliderWorldVertices = [];
  18597. subMesh._trianglePlanes = [];
  18598. var start = subMesh.verticesStart;
  18599. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18600. for (var i = start; i < end; i++) {
  18601. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18602. }
  18603. }
  18604. // Collide
  18605. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18606. if (collider.collisionFound) {
  18607. collider.collidedMesh = this;
  18608. }
  18609. return this;
  18610. };
  18611. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18612. var subMeshes;
  18613. var len;
  18614. // Octrees
  18615. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18616. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18617. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18618. len = intersections.length;
  18619. subMeshes = intersections.data;
  18620. }
  18621. else {
  18622. subMeshes = this.subMeshes;
  18623. len = subMeshes.length;
  18624. }
  18625. for (var index = 0; index < len; index++) {
  18626. var subMesh = subMeshes[index];
  18627. // Bounding test
  18628. if (len > 1 && !subMesh._checkCollision(collider))
  18629. continue;
  18630. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18631. }
  18632. return this;
  18633. };
  18634. AbstractMesh.prototype._checkCollision = function (collider) {
  18635. // Bounding box test
  18636. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18637. return this;
  18638. // Transformation matrix
  18639. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18640. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18641. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18642. return this;
  18643. };
  18644. // Picking
  18645. AbstractMesh.prototype._generatePointsArray = function () {
  18646. return false;
  18647. };
  18648. /**
  18649. * Checks if the passed Ray intersects with the mesh.
  18650. * Returns an object PickingInfo.
  18651. */
  18652. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18653. var pickingInfo = new BABYLON.PickingInfo();
  18654. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18655. return pickingInfo;
  18656. }
  18657. if (!this._generatePointsArray()) {
  18658. return pickingInfo;
  18659. }
  18660. var intersectInfo = null;
  18661. // Octrees
  18662. var subMeshes;
  18663. var len;
  18664. if (this._submeshesOctree && this.useOctreeForPicking) {
  18665. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18666. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18667. len = intersections.length;
  18668. subMeshes = intersections.data;
  18669. }
  18670. else {
  18671. subMeshes = this.subMeshes;
  18672. len = subMeshes.length;
  18673. }
  18674. for (var index = 0; index < len; index++) {
  18675. var subMesh = subMeshes[index];
  18676. // Bounding test
  18677. if (len > 1 && !subMesh.canIntersects(ray))
  18678. continue;
  18679. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18680. if (currentIntersectInfo) {
  18681. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18682. intersectInfo = currentIntersectInfo;
  18683. intersectInfo.subMeshId = index;
  18684. if (fastCheck) {
  18685. break;
  18686. }
  18687. }
  18688. }
  18689. }
  18690. if (intersectInfo) {
  18691. // Get picked point
  18692. var world = this.getWorldMatrix();
  18693. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18694. var direction = ray.direction.clone();
  18695. direction = direction.scale(intersectInfo.distance);
  18696. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18697. var pickedPoint = worldOrigin.add(worldDirection);
  18698. // Return result
  18699. pickingInfo.hit = true;
  18700. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18701. pickingInfo.pickedPoint = pickedPoint;
  18702. pickingInfo.pickedMesh = this;
  18703. pickingInfo.bu = intersectInfo.bu || 0;
  18704. pickingInfo.bv = intersectInfo.bv || 0;
  18705. pickingInfo.faceId = intersectInfo.faceId;
  18706. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18707. return pickingInfo;
  18708. }
  18709. return pickingInfo;
  18710. };
  18711. /**
  18712. * Clones the mesh, used by the class Mesh.
  18713. * Just returns `null` for an AbstractMesh.
  18714. */
  18715. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18716. return null;
  18717. };
  18718. /**
  18719. * Disposes all the mesh submeshes.
  18720. * Returns the AbstractMesh.
  18721. */
  18722. AbstractMesh.prototype.releaseSubMeshes = function () {
  18723. if (this.subMeshes) {
  18724. while (this.subMeshes.length) {
  18725. this.subMeshes[0].dispose();
  18726. }
  18727. }
  18728. else {
  18729. this.subMeshes = new Array();
  18730. }
  18731. return this;
  18732. };
  18733. /**
  18734. * Releases resources associated with this abstract mesh.
  18735. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18736. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18737. */
  18738. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18739. var _this = this;
  18740. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18741. var index;
  18742. // Smart Array Retainers.
  18743. this.getScene().freeActiveMeshes();
  18744. this.getScene().freeRenderingGroups();
  18745. // Action manager
  18746. if (this.actionManager !== undefined && this.actionManager !== null) {
  18747. this.actionManager.dispose();
  18748. this.actionManager = null;
  18749. }
  18750. // Skeleton
  18751. this._skeleton = null;
  18752. // Physics
  18753. if (this.physicsImpostor) {
  18754. this.physicsImpostor.dispose();
  18755. }
  18756. // Intersections in progress
  18757. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18758. var other = this._intersectionsInProgress[index];
  18759. var pos = other._intersectionsInProgress.indexOf(this);
  18760. other._intersectionsInProgress.splice(pos, 1);
  18761. }
  18762. this._intersectionsInProgress = [];
  18763. // Lights
  18764. var lights = this.getScene().lights;
  18765. lights.forEach(function (light) {
  18766. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18767. if (meshIndex !== -1) {
  18768. light.includedOnlyMeshes.splice(meshIndex, 1);
  18769. }
  18770. meshIndex = light.excludedMeshes.indexOf(_this);
  18771. if (meshIndex !== -1) {
  18772. light.excludedMeshes.splice(meshIndex, 1);
  18773. }
  18774. // Shadow generators
  18775. var generator = light.getShadowGenerator();
  18776. if (generator) {
  18777. var shadowMap = generator.getShadowMap();
  18778. if (shadowMap && shadowMap.renderList) {
  18779. meshIndex = shadowMap.renderList.indexOf(_this);
  18780. if (meshIndex !== -1) {
  18781. shadowMap.renderList.splice(meshIndex, 1);
  18782. }
  18783. }
  18784. }
  18785. });
  18786. // Edges
  18787. if (this._edgesRenderer) {
  18788. this._edgesRenderer.dispose();
  18789. this._edgesRenderer = null;
  18790. }
  18791. // SubMeshes
  18792. if (this.getClassName() !== "InstancedMesh") {
  18793. this.releaseSubMeshes();
  18794. }
  18795. // Octree
  18796. var sceneOctree = this.getScene().selectionOctree;
  18797. if (sceneOctree !== undefined && sceneOctree !== null) {
  18798. var index = sceneOctree.dynamicContent.indexOf(this);
  18799. if (index !== -1) {
  18800. sceneOctree.dynamicContent.splice(index, 1);
  18801. }
  18802. }
  18803. // Query
  18804. var engine = this.getScene().getEngine();
  18805. if (this._occlusionQuery) {
  18806. this._isOcclusionQueryInProgress = false;
  18807. engine.deleteQuery(this._occlusionQuery);
  18808. this._occlusionQuery = null;
  18809. }
  18810. // Engine
  18811. engine.wipeCaches();
  18812. // Remove from scene
  18813. this.getScene().removeMesh(this);
  18814. if (disposeMaterialAndTextures) {
  18815. if (this.material) {
  18816. this.material.dispose(false, true);
  18817. }
  18818. }
  18819. if (!doNotRecurse) {
  18820. // Particles
  18821. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18822. if (this.getScene().particleSystems[index].emitter === this) {
  18823. this.getScene().particleSystems[index].dispose();
  18824. index--;
  18825. }
  18826. }
  18827. }
  18828. // facet data
  18829. if (this._facetDataEnabled) {
  18830. this.disableFacetData();
  18831. }
  18832. this.onAfterWorldMatrixUpdateObservable.clear();
  18833. this.onCollideObservable.clear();
  18834. this.onCollisionPositionChangeObservable.clear();
  18835. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18836. };
  18837. /**
  18838. * Adds the passed mesh as a child to the current mesh.
  18839. * Returns the AbstractMesh.
  18840. */
  18841. AbstractMesh.prototype.addChild = function (mesh) {
  18842. mesh.setParent(this);
  18843. return this;
  18844. };
  18845. /**
  18846. * Removes the passed mesh from the current mesh children list.
  18847. * Returns the AbstractMesh.
  18848. */
  18849. AbstractMesh.prototype.removeChild = function (mesh) {
  18850. mesh.setParent(null);
  18851. return this;
  18852. };
  18853. // Facet data
  18854. /**
  18855. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18856. * Returns the AbstractMesh.
  18857. */
  18858. AbstractMesh.prototype._initFacetData = function () {
  18859. if (!this._facetNormals) {
  18860. this._facetNormals = new Array();
  18861. }
  18862. if (!this._facetPositions) {
  18863. this._facetPositions = new Array();
  18864. }
  18865. if (!this._facetPartitioning) {
  18866. this._facetPartitioning = new Array();
  18867. }
  18868. this._facetNb = (this.getIndices().length / 3) | 0;
  18869. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18870. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18871. for (var f = 0; f < this._facetNb; f++) {
  18872. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18873. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18874. }
  18875. this._facetDataEnabled = true;
  18876. return this;
  18877. };
  18878. /**
  18879. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18880. * This method can be called within the render loop.
  18881. * 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.
  18882. * Returns the AbstractMesh.
  18883. */
  18884. AbstractMesh.prototype.updateFacetData = function () {
  18885. if (!this._facetDataEnabled) {
  18886. this._initFacetData();
  18887. }
  18888. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18889. var indices = this.getIndices();
  18890. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18891. var bInfo = this.getBoundingInfo();
  18892. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18893. // init arrays, matrix and sort function on first call
  18894. this._facetDepthSortEnabled = true;
  18895. if (indices instanceof Uint16Array) {
  18896. this._depthSortedIndices = new Uint16Array(indices);
  18897. }
  18898. else if (indices instanceof Uint32Array) {
  18899. this._depthSortedIndices = new Uint32Array(indices);
  18900. }
  18901. else {
  18902. var needs32bits = false;
  18903. for (var i = 0; i < indices.length; i++) {
  18904. if (indices[i] > 65535) {
  18905. needs32bits = true;
  18906. break;
  18907. }
  18908. }
  18909. if (needs32bits) {
  18910. this._depthSortedIndices = new Uint32Array(indices);
  18911. }
  18912. else {
  18913. this._depthSortedIndices = new Uint16Array(indices);
  18914. }
  18915. }
  18916. this._facetDepthSortFunction = function (f1, f2) {
  18917. return (f2.sqDistance - f1.sqDistance);
  18918. };
  18919. if (!this._facetDepthSortFrom) {
  18920. var camera = this.getScene().activeCamera;
  18921. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18922. }
  18923. this._depthSortedFacets = [];
  18924. for (var f = 0; f < this._facetNb; f++) {
  18925. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18926. this._depthSortedFacets.push(depthSortedFacet);
  18927. }
  18928. this._invertedMatrix = BABYLON.Matrix.Identity();
  18929. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18930. }
  18931. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18932. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18933. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18934. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18935. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18936. this._subDiv.max = this._partitioningSubdivisions;
  18937. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18938. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18939. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18940. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18941. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18942. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18943. // set the parameters for ComputeNormals()
  18944. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18945. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18946. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18947. this._facetParameters.bInfo = bInfo;
  18948. this._facetParameters.bbSize = this._bbSize;
  18949. this._facetParameters.subDiv = this._subDiv;
  18950. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18951. this._facetParameters.depthSort = this._facetDepthSort;
  18952. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18953. this.computeWorldMatrix(true);
  18954. this._worldMatrix.invertToRef(this._invertedMatrix);
  18955. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18956. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18957. }
  18958. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18959. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18960. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18961. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18962. var l = (this._depthSortedIndices.length / 3) | 0;
  18963. for (var f = 0; f < l; f++) {
  18964. var sind = this._depthSortedFacets[f].ind;
  18965. this._depthSortedIndices[f * 3] = indices[sind];
  18966. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18967. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18968. }
  18969. this.updateIndices(this._depthSortedIndices);
  18970. }
  18971. return this;
  18972. };
  18973. /**
  18974. * Returns the facetLocalNormals array.
  18975. * The normals are expressed in the mesh local space.
  18976. */
  18977. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18978. if (!this._facetNormals) {
  18979. this.updateFacetData();
  18980. }
  18981. return this._facetNormals;
  18982. };
  18983. /**
  18984. * Returns the facetLocalPositions array.
  18985. * The facet positions are expressed in the mesh local space.
  18986. */
  18987. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18988. if (!this._facetPositions) {
  18989. this.updateFacetData();
  18990. }
  18991. return this._facetPositions;
  18992. };
  18993. /**
  18994. * Returns the facetLocalPartioning array.
  18995. */
  18996. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18997. if (!this._facetPartitioning) {
  18998. this.updateFacetData();
  18999. }
  19000. return this._facetPartitioning;
  19001. };
  19002. /**
  19003. * Returns the i-th facet position in the world system.
  19004. * This method allocates a new Vector3 per call.
  19005. */
  19006. AbstractMesh.prototype.getFacetPosition = function (i) {
  19007. var pos = BABYLON.Vector3.Zero();
  19008. this.getFacetPositionToRef(i, pos);
  19009. return pos;
  19010. };
  19011. /**
  19012. * Sets the reference Vector3 with the i-th facet position in the world system.
  19013. * Returns the AbstractMesh.
  19014. */
  19015. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  19016. var localPos = (this.getFacetLocalPositions())[i];
  19017. var world = this.getWorldMatrix();
  19018. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  19019. return this;
  19020. };
  19021. /**
  19022. * Returns the i-th facet normal in the world system.
  19023. * This method allocates a new Vector3 per call.
  19024. */
  19025. AbstractMesh.prototype.getFacetNormal = function (i) {
  19026. var norm = BABYLON.Vector3.Zero();
  19027. this.getFacetNormalToRef(i, norm);
  19028. return norm;
  19029. };
  19030. /**
  19031. * Sets the reference Vector3 with the i-th facet normal in the world system.
  19032. * Returns the AbstractMesh.
  19033. */
  19034. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  19035. var localNorm = (this.getFacetLocalNormals())[i];
  19036. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  19037. return this;
  19038. };
  19039. /**
  19040. * 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).
  19041. */
  19042. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  19043. var bInfo = this.getBoundingInfo();
  19044. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  19045. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  19046. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  19047. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  19048. return null;
  19049. }
  19050. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  19051. };
  19052. /**
  19053. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  19054. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  19055. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  19056. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19057. * 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.
  19058. */
  19059. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  19060. if (checkFace === void 0) { checkFace = false; }
  19061. if (facing === void 0) { facing = true; }
  19062. var world = this.getWorldMatrix();
  19063. var invMat = BABYLON.Tmp.Matrix[5];
  19064. world.invertToRef(invMat);
  19065. var invVect = BABYLON.Tmp.Vector3[8];
  19066. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  19067. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  19068. if (projected) {
  19069. // tranform the local computed projected vector to world coordinates
  19070. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  19071. }
  19072. return closest;
  19073. };
  19074. /**
  19075. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  19076. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  19077. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  19078. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19079. * 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.
  19080. */
  19081. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  19082. if (checkFace === void 0) { checkFace = false; }
  19083. if (facing === void 0) { facing = true; }
  19084. var closest = null;
  19085. var tmpx = 0.0;
  19086. var tmpy = 0.0;
  19087. var tmpz = 0.0;
  19088. var d = 0.0; // tmp dot facet normal * facet position
  19089. var t0 = 0.0;
  19090. var projx = 0.0;
  19091. var projy = 0.0;
  19092. var projz = 0.0;
  19093. // Get all the facets in the same partitioning block than (x, y, z)
  19094. var facetPositions = this.getFacetLocalPositions();
  19095. var facetNormals = this.getFacetLocalNormals();
  19096. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  19097. if (!facetsInBlock) {
  19098. return null;
  19099. }
  19100. // Get the closest facet to (x, y, z)
  19101. var shortest = Number.MAX_VALUE; // init distance vars
  19102. var tmpDistance = shortest;
  19103. var fib; // current facet in the block
  19104. var norm; // current facet normal
  19105. var p0; // current facet barycenter position
  19106. // loop on all the facets in the current partitioning block
  19107. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  19108. fib = facetsInBlock[idx];
  19109. norm = facetNormals[fib];
  19110. p0 = facetPositions[fib];
  19111. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  19112. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  19113. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  19114. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  19115. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  19116. projx = x + norm.x * t0;
  19117. projy = y + norm.y * t0;
  19118. projz = z + norm.z * t0;
  19119. tmpx = projx - x;
  19120. tmpy = projy - y;
  19121. tmpz = projz - z;
  19122. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  19123. if (tmpDistance < shortest) {
  19124. shortest = tmpDistance;
  19125. closest = fib;
  19126. if (projected) {
  19127. projected.x = projx;
  19128. projected.y = projy;
  19129. projected.z = projz;
  19130. }
  19131. }
  19132. }
  19133. }
  19134. return closest;
  19135. };
  19136. /**
  19137. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  19138. */
  19139. AbstractMesh.prototype.getFacetDataParameters = function () {
  19140. return this._facetParameters;
  19141. };
  19142. /**
  19143. * Disables the feature FacetData and frees the related memory.
  19144. * Returns the AbstractMesh.
  19145. */
  19146. AbstractMesh.prototype.disableFacetData = function () {
  19147. if (this._facetDataEnabled) {
  19148. this._facetDataEnabled = false;
  19149. this._facetPositions = new Array();
  19150. this._facetNormals = new Array();
  19151. this._facetPartitioning = new Array();
  19152. this._facetParameters = null;
  19153. this._depthSortedIndices = new Uint32Array(0);
  19154. }
  19155. return this;
  19156. };
  19157. /**
  19158. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  19159. * Returns the mesh.
  19160. */
  19161. AbstractMesh.prototype.updateIndices = function (indices) {
  19162. return this;
  19163. };
  19164. /**
  19165. * The mesh Geometry. Actually used by the Mesh object.
  19166. * Returns a blank geometry object.
  19167. */
  19168. /**
  19169. * Creates new normals data for the mesh.
  19170. * @param updatable.
  19171. */
  19172. AbstractMesh.prototype.createNormals = function (updatable) {
  19173. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19174. var indices = this.getIndices();
  19175. var normals;
  19176. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19177. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19178. }
  19179. else {
  19180. normals = [];
  19181. }
  19182. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19183. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19184. };
  19185. /**
  19186. * Align the mesh with a normal.
  19187. * Returns the mesh.
  19188. */
  19189. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19190. if (!upDirection) {
  19191. upDirection = BABYLON.Axis.Y;
  19192. }
  19193. var axisX = BABYLON.Tmp.Vector3[0];
  19194. var axisZ = BABYLON.Tmp.Vector3[1];
  19195. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19196. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19197. if (this.rotationQuaternion) {
  19198. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19199. }
  19200. else {
  19201. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19202. }
  19203. return this;
  19204. };
  19205. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19206. var engine = this.getEngine();
  19207. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19208. this._isOccluded = false;
  19209. return;
  19210. }
  19211. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19212. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19213. if (isOcclusionQueryAvailable) {
  19214. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19215. this._isOcclusionQueryInProgress = false;
  19216. this._occlusionInternalRetryCounter = 0;
  19217. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19218. }
  19219. else {
  19220. this._occlusionInternalRetryCounter++;
  19221. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19222. this._isOcclusionQueryInProgress = false;
  19223. this._occlusionInternalRetryCounter = 0;
  19224. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19225. // if strict continue the last state of the object.
  19226. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19227. }
  19228. else {
  19229. return;
  19230. }
  19231. }
  19232. }
  19233. var scene = this.getScene();
  19234. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19235. if (!this._occlusionQuery) {
  19236. this._occlusionQuery = engine.createQuery();
  19237. }
  19238. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19239. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19240. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19241. this._isOcclusionQueryInProgress = true;
  19242. };
  19243. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19244. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19245. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19246. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19247. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19248. return AbstractMesh;
  19249. }(BABYLON.TransformNode));
  19250. BABYLON.AbstractMesh = AbstractMesh;
  19251. })(BABYLON || (BABYLON = {}));
  19252. //# sourceMappingURL=babylon.abstractMesh.js.map
  19253. "use strict";
  19254. var BABYLON;
  19255. (function (BABYLON) {
  19256. /**
  19257. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19258. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19259. * 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.
  19260. */
  19261. var Light = /** @class */ (function (_super) {
  19262. __extends(Light, _super);
  19263. /**
  19264. * Creates a Light object in the scene.
  19265. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19266. * @param name The firendly name of the light
  19267. * @param scene The scene the light belongs too
  19268. */
  19269. function Light(name, scene) {
  19270. var _this = _super.call(this, name, scene) || this;
  19271. /**
  19272. * Diffuse gives the basic color to an object.
  19273. */
  19274. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19275. /**
  19276. * Specular produces a highlight color on an object.
  19277. * Note: This is note affecting PBR materials.
  19278. */
  19279. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19280. /**
  19281. * Strength of the light.
  19282. * Note: By default it is define in the framework own unit.
  19283. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19284. */
  19285. _this.intensity = 1.0;
  19286. /**
  19287. * Defines how far from the source the light is impacting in scene units.
  19288. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19289. */
  19290. _this.range = Number.MAX_VALUE;
  19291. /**
  19292. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19293. * of light.
  19294. */
  19295. _this._photometricScale = 1.0;
  19296. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19297. _this._radius = 0.00001;
  19298. /**
  19299. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19300. * exceeding the number allowed of the materials.
  19301. */
  19302. _this.renderPriority = 0;
  19303. /**
  19304. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19305. * the current shadow generator.
  19306. */
  19307. _this.shadowEnabled = true;
  19308. _this._excludeWithLayerMask = 0;
  19309. _this._includeOnlyWithLayerMask = 0;
  19310. _this._lightmapMode = 0;
  19311. /**
  19312. * @ignore Internal use only.
  19313. */
  19314. _this._excludedMeshesIds = new Array();
  19315. /**
  19316. * @ignore Internal use only.
  19317. */
  19318. _this._includedOnlyMeshesIds = new Array();
  19319. _this.getScene().addLight(_this);
  19320. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19321. _this._buildUniformLayout();
  19322. _this.includedOnlyMeshes = new Array();
  19323. _this.excludedMeshes = new Array();
  19324. _this._resyncMeshes();
  19325. return _this;
  19326. }
  19327. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19328. /**
  19329. * If every light affecting the material is in this lightmapMode,
  19330. * material.lightmapTexture adds or multiplies
  19331. * (depends on material.useLightmapAsShadowmap)
  19332. * after every other light calculations.
  19333. */
  19334. get: function () {
  19335. return Light._LIGHTMAP_DEFAULT;
  19336. },
  19337. enumerable: true,
  19338. configurable: true
  19339. });
  19340. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19341. /**
  19342. * material.lightmapTexture as only diffuse lighting from this light
  19343. * adds only specular lighting from this light
  19344. * adds dynamic shadows
  19345. */
  19346. get: function () {
  19347. return Light._LIGHTMAP_SPECULAR;
  19348. },
  19349. enumerable: true,
  19350. configurable: true
  19351. });
  19352. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19353. /**
  19354. * material.lightmapTexture as only lighting
  19355. * no light calculation from this light
  19356. * only adds dynamic shadows from this light
  19357. */
  19358. get: function () {
  19359. return Light._LIGHTMAP_SHADOWSONLY;
  19360. },
  19361. enumerable: true,
  19362. configurable: true
  19363. });
  19364. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19365. /**
  19366. * Each light type uses the default quantity according to its type:
  19367. * point/spot lights use luminous intensity
  19368. * directional lights use illuminance
  19369. */
  19370. get: function () {
  19371. return Light._INTENSITYMODE_AUTOMATIC;
  19372. },
  19373. enumerable: true,
  19374. configurable: true
  19375. });
  19376. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19377. /**
  19378. * lumen (lm)
  19379. */
  19380. get: function () {
  19381. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19382. },
  19383. enumerable: true,
  19384. configurable: true
  19385. });
  19386. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19387. /**
  19388. * candela (lm/sr)
  19389. */
  19390. get: function () {
  19391. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19392. },
  19393. enumerable: true,
  19394. configurable: true
  19395. });
  19396. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19397. /**
  19398. * lux (lm/m^2)
  19399. */
  19400. get: function () {
  19401. return Light._INTENSITYMODE_ILLUMINANCE;
  19402. },
  19403. enumerable: true,
  19404. configurable: true
  19405. });
  19406. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19407. /**
  19408. * nit (cd/m^2)
  19409. */
  19410. get: function () {
  19411. return Light._INTENSITYMODE_LUMINANCE;
  19412. },
  19413. enumerable: true,
  19414. configurable: true
  19415. });
  19416. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19417. /**
  19418. * Light type const id of the point light.
  19419. */
  19420. get: function () {
  19421. return Light._LIGHTTYPEID_POINTLIGHT;
  19422. },
  19423. enumerable: true,
  19424. configurable: true
  19425. });
  19426. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19427. /**
  19428. * Light type const id of the directional light.
  19429. */
  19430. get: function () {
  19431. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19432. },
  19433. enumerable: true,
  19434. configurable: true
  19435. });
  19436. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19437. /**
  19438. * Light type const id of the spot light.
  19439. */
  19440. get: function () {
  19441. return Light._LIGHTTYPEID_SPOTLIGHT;
  19442. },
  19443. enumerable: true,
  19444. configurable: true
  19445. });
  19446. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19447. /**
  19448. * Light type const id of the hemispheric light.
  19449. */
  19450. get: function () {
  19451. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19452. },
  19453. enumerable: true,
  19454. configurable: true
  19455. });
  19456. Object.defineProperty(Light.prototype, "intensityMode", {
  19457. /**
  19458. * Gets the photometric scale used to interpret the intensity.
  19459. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19460. */
  19461. get: function () {
  19462. return this._intensityMode;
  19463. },
  19464. /**
  19465. * Sets the photometric scale used to interpret the intensity.
  19466. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19467. */
  19468. set: function (value) {
  19469. this._intensityMode = value;
  19470. this._computePhotometricScale();
  19471. },
  19472. enumerable: true,
  19473. configurable: true
  19474. });
  19475. ;
  19476. ;
  19477. Object.defineProperty(Light.prototype, "radius", {
  19478. /**
  19479. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19480. */
  19481. get: function () {
  19482. return this._radius;
  19483. },
  19484. /**
  19485. * sets the light radius used by PBR Materials to simulate soft area lights.
  19486. */
  19487. set: function (value) {
  19488. this._radius = value;
  19489. this._computePhotometricScale();
  19490. },
  19491. enumerable: true,
  19492. configurable: true
  19493. });
  19494. ;
  19495. ;
  19496. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19497. /**
  19498. * Gets the only meshes impacted by this light.
  19499. */
  19500. get: function () {
  19501. return this._includedOnlyMeshes;
  19502. },
  19503. /**
  19504. * Sets the only meshes impacted by this light.
  19505. */
  19506. set: function (value) {
  19507. this._includedOnlyMeshes = value;
  19508. this._hookArrayForIncludedOnly(value);
  19509. },
  19510. enumerable: true,
  19511. configurable: true
  19512. });
  19513. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19514. /**
  19515. * Gets the meshes not impacted by this light.
  19516. */
  19517. get: function () {
  19518. return this._excludedMeshes;
  19519. },
  19520. /**
  19521. * Sets the meshes not impacted by this light.
  19522. */
  19523. set: function (value) {
  19524. this._excludedMeshes = value;
  19525. this._hookArrayForExcluded(value);
  19526. },
  19527. enumerable: true,
  19528. configurable: true
  19529. });
  19530. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19531. /**
  19532. * Gets the layer id use to find what meshes are not impacted by the light.
  19533. * Inactive if 0
  19534. */
  19535. get: function () {
  19536. return this._excludeWithLayerMask;
  19537. },
  19538. /**
  19539. * Sets the layer id use to find what meshes are not impacted by the light.
  19540. * Inactive if 0
  19541. */
  19542. set: function (value) {
  19543. this._excludeWithLayerMask = value;
  19544. this._resyncMeshes();
  19545. },
  19546. enumerable: true,
  19547. configurable: true
  19548. });
  19549. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19550. /**
  19551. * Gets the layer id use to find what meshes are impacted by the light.
  19552. * Inactive if 0
  19553. */
  19554. get: function () {
  19555. return this._includeOnlyWithLayerMask;
  19556. },
  19557. /**
  19558. * Sets the layer id use to find what meshes are impacted by the light.
  19559. * Inactive if 0
  19560. */
  19561. set: function (value) {
  19562. this._includeOnlyWithLayerMask = value;
  19563. this._resyncMeshes();
  19564. },
  19565. enumerable: true,
  19566. configurable: true
  19567. });
  19568. Object.defineProperty(Light.prototype, "lightmapMode", {
  19569. /**
  19570. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19571. */
  19572. get: function () {
  19573. return this._lightmapMode;
  19574. },
  19575. /**
  19576. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19577. */
  19578. set: function (value) {
  19579. if (this._lightmapMode === value) {
  19580. return;
  19581. }
  19582. this._lightmapMode = value;
  19583. this._markMeshesAsLightDirty();
  19584. },
  19585. enumerable: true,
  19586. configurable: true
  19587. });
  19588. /**
  19589. * Returns the string "Light".
  19590. * @returns the class name
  19591. */
  19592. Light.prototype.getClassName = function () {
  19593. return "Light";
  19594. };
  19595. /**
  19596. * Converts the light information to a readable string for debug purpose.
  19597. * @param fullDetails Supports for multiple levels of logging within scene loading
  19598. * @returns the human readable light info
  19599. */
  19600. Light.prototype.toString = function (fullDetails) {
  19601. var ret = "Name: " + this.name;
  19602. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19603. if (this.animations) {
  19604. for (var i = 0; i < this.animations.length; i++) {
  19605. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19606. }
  19607. }
  19608. if (fullDetails) {
  19609. }
  19610. return ret;
  19611. };
  19612. /**
  19613. * Set the enabled state of this node.
  19614. * @param value - the new enabled state
  19615. * @see isEnabled
  19616. */
  19617. Light.prototype.setEnabled = function (value) {
  19618. _super.prototype.setEnabled.call(this, value);
  19619. this._resyncMeshes();
  19620. };
  19621. /**
  19622. * Returns the Light associated shadow generator if any.
  19623. * @return the associated shadow generator.
  19624. */
  19625. Light.prototype.getShadowGenerator = function () {
  19626. return this._shadowGenerator;
  19627. };
  19628. /**
  19629. * Returns a Vector3, the absolute light position in the World.
  19630. * @returns the world space position of the light
  19631. */
  19632. Light.prototype.getAbsolutePosition = function () {
  19633. return BABYLON.Vector3.Zero();
  19634. };
  19635. /**
  19636. * Specifies if the light will affect the passed mesh.
  19637. * @param mesh The mesh to test against the light
  19638. * @return true the mesh is affected otherwise, false.
  19639. */
  19640. Light.prototype.canAffectMesh = function (mesh) {
  19641. if (!mesh) {
  19642. return true;
  19643. }
  19644. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19645. return false;
  19646. }
  19647. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19648. return false;
  19649. }
  19650. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19651. return false;
  19652. }
  19653. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19654. return false;
  19655. }
  19656. return true;
  19657. };
  19658. /**
  19659. * Computes and Returns the light World matrix.
  19660. * @returns the world matrix
  19661. */
  19662. Light.prototype.getWorldMatrix = function () {
  19663. this._currentRenderId = this.getScene().getRenderId();
  19664. var worldMatrix = this._getWorldMatrix();
  19665. if (this.parent && this.parent.getWorldMatrix) {
  19666. if (!this._parentedWorldMatrix) {
  19667. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19668. }
  19669. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19670. this._markSyncedWithParent();
  19671. return this._parentedWorldMatrix;
  19672. }
  19673. return worldMatrix;
  19674. };
  19675. /**
  19676. * Sort function to order lights for rendering.
  19677. * @param a First Light object to compare to second.
  19678. * @param b Second Light object to compare first.
  19679. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19680. */
  19681. Light.CompareLightsPriority = function (a, b) {
  19682. //shadow-casting lights have priority over non-shadow-casting lights
  19683. //the renderPrioirty is a secondary sort criterion
  19684. if (a.shadowEnabled !== b.shadowEnabled) {
  19685. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19686. }
  19687. return b.renderPriority - a.renderPriority;
  19688. };
  19689. /**
  19690. * Releases resources associated with this node.
  19691. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19692. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19693. */
  19694. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19695. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19696. if (this._shadowGenerator) {
  19697. this._shadowGenerator.dispose();
  19698. this._shadowGenerator = null;
  19699. }
  19700. // Animations
  19701. this.getScene().stopAnimation(this);
  19702. // Remove from meshes
  19703. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19704. var mesh = _a[_i];
  19705. mesh._removeLightSource(this);
  19706. }
  19707. this._uniformBuffer.dispose();
  19708. // Remove from scene
  19709. this.getScene().removeLight(this);
  19710. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19711. };
  19712. /**
  19713. * Returns the light type ID (integer).
  19714. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19715. */
  19716. Light.prototype.getTypeID = function () {
  19717. return 0;
  19718. };
  19719. /**
  19720. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19721. * @returns the scaled intensity in intensity mode unit
  19722. */
  19723. Light.prototype.getScaledIntensity = function () {
  19724. return this._photometricScale * this.intensity;
  19725. };
  19726. /**
  19727. * Returns a new Light object, named "name", from the current one.
  19728. * @param name The name of the cloned light
  19729. * @returns the new created light
  19730. */
  19731. Light.prototype.clone = function (name) {
  19732. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19733. if (!constructor) {
  19734. return null;
  19735. }
  19736. return BABYLON.SerializationHelper.Clone(constructor, this);
  19737. };
  19738. /**
  19739. * Serializes the current light into a Serialization object.
  19740. * @returns the serialized object.
  19741. */
  19742. Light.prototype.serialize = function () {
  19743. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19744. // Type
  19745. serializationObject.type = this.getTypeID();
  19746. // Parent
  19747. if (this.parent) {
  19748. serializationObject.parentId = this.parent.id;
  19749. }
  19750. // Inclusion / exclusions
  19751. if (this.excludedMeshes.length > 0) {
  19752. serializationObject.excludedMeshesIds = [];
  19753. this.excludedMeshes.forEach(function (mesh) {
  19754. serializationObject.excludedMeshesIds.push(mesh.id);
  19755. });
  19756. }
  19757. if (this.includedOnlyMeshes.length > 0) {
  19758. serializationObject.includedOnlyMeshesIds = [];
  19759. this.includedOnlyMeshes.forEach(function (mesh) {
  19760. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19761. });
  19762. }
  19763. // Animations
  19764. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19765. serializationObject.ranges = this.serializeAnimationRanges();
  19766. return serializationObject;
  19767. };
  19768. /**
  19769. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19770. * This new light is named "name" and added to the passed scene.
  19771. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19772. * @param name The friendly name of the light
  19773. * @param scene The scene the new light will belong to
  19774. * @returns the constructor function
  19775. */
  19776. Light.GetConstructorFromName = function (type, name, scene) {
  19777. switch (type) {
  19778. case 0:
  19779. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19780. case 1:
  19781. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19782. case 2:
  19783. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19784. case 3:
  19785. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19786. }
  19787. return null;
  19788. };
  19789. /**
  19790. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19791. * @param parsedLight The JSON representation of the light
  19792. * @param scene The scene to create the parsed light in
  19793. * @returns the created light after parsing
  19794. */
  19795. Light.Parse = function (parsedLight, scene) {
  19796. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19797. if (!constructor) {
  19798. return null;
  19799. }
  19800. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19801. // Inclusion / exclusions
  19802. if (parsedLight.excludedMeshesIds) {
  19803. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19804. }
  19805. if (parsedLight.includedOnlyMeshesIds) {
  19806. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19807. }
  19808. // Parent
  19809. if (parsedLight.parentId) {
  19810. light._waitingParentId = parsedLight.parentId;
  19811. }
  19812. // Animations
  19813. if (parsedLight.animations) {
  19814. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19815. var parsedAnimation = parsedLight.animations[animationIndex];
  19816. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19817. }
  19818. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19819. }
  19820. if (parsedLight.autoAnimate) {
  19821. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19822. }
  19823. return light;
  19824. };
  19825. Light.prototype._hookArrayForExcluded = function (array) {
  19826. var _this = this;
  19827. var oldPush = array.push;
  19828. array.push = function () {
  19829. var items = [];
  19830. for (var _i = 0; _i < arguments.length; _i++) {
  19831. items[_i] = arguments[_i];
  19832. }
  19833. var result = oldPush.apply(array, items);
  19834. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19835. var item = items_1[_a];
  19836. item._resyncLighSource(_this);
  19837. }
  19838. return result;
  19839. };
  19840. var oldSplice = array.splice;
  19841. array.splice = function (index, deleteCount) {
  19842. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19843. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19844. var item = deleted_1[_i];
  19845. item._resyncLighSource(_this);
  19846. }
  19847. return deleted;
  19848. };
  19849. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19850. var item = array_1[_i];
  19851. item._resyncLighSource(this);
  19852. }
  19853. };
  19854. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19855. var _this = this;
  19856. var oldPush = array.push;
  19857. array.push = function () {
  19858. var items = [];
  19859. for (var _i = 0; _i < arguments.length; _i++) {
  19860. items[_i] = arguments[_i];
  19861. }
  19862. var result = oldPush.apply(array, items);
  19863. _this._resyncMeshes();
  19864. return result;
  19865. };
  19866. var oldSplice = array.splice;
  19867. array.splice = function (index, deleteCount) {
  19868. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19869. _this._resyncMeshes();
  19870. return deleted;
  19871. };
  19872. this._resyncMeshes();
  19873. };
  19874. Light.prototype._resyncMeshes = function () {
  19875. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19876. var mesh = _a[_i];
  19877. mesh._resyncLighSource(this);
  19878. }
  19879. };
  19880. /**
  19881. * Forces the meshes to update their light related information in their rendering used effects
  19882. * @ignore Internal Use Only
  19883. */
  19884. Light.prototype._markMeshesAsLightDirty = function () {
  19885. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19886. var mesh = _a[_i];
  19887. if (mesh._lightSources.indexOf(this) !== -1) {
  19888. mesh._markSubMeshesAsLightDirty();
  19889. }
  19890. }
  19891. };
  19892. /**
  19893. * Recomputes the cached photometric scale if needed.
  19894. */
  19895. Light.prototype._computePhotometricScale = function () {
  19896. this._photometricScale = this._getPhotometricScale();
  19897. this.getScene().resetCachedMaterial();
  19898. };
  19899. /**
  19900. * Returns the Photometric Scale according to the light type and intensity mode.
  19901. */
  19902. Light.prototype._getPhotometricScale = function () {
  19903. var photometricScale = 0.0;
  19904. var lightTypeID = this.getTypeID();
  19905. //get photometric mode
  19906. var photometricMode = this.intensityMode;
  19907. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19908. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19909. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19910. }
  19911. else {
  19912. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19913. }
  19914. }
  19915. //compute photometric scale
  19916. switch (lightTypeID) {
  19917. case Light.LIGHTTYPEID_POINTLIGHT:
  19918. case Light.LIGHTTYPEID_SPOTLIGHT:
  19919. switch (photometricMode) {
  19920. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19921. photometricScale = 1.0 / (4.0 * Math.PI);
  19922. break;
  19923. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19924. photometricScale = 1.0;
  19925. break;
  19926. case Light.INTENSITYMODE_LUMINANCE:
  19927. photometricScale = this.radius * this.radius;
  19928. break;
  19929. }
  19930. break;
  19931. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19932. switch (photometricMode) {
  19933. case Light.INTENSITYMODE_ILLUMINANCE:
  19934. photometricScale = 1.0;
  19935. break;
  19936. case Light.INTENSITYMODE_LUMINANCE:
  19937. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19938. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19939. var apexAngleRadians = this.radius;
  19940. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19941. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19942. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19943. photometricScale = solidAngle;
  19944. break;
  19945. }
  19946. break;
  19947. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19948. // No fall off in hemisperic light.
  19949. photometricScale = 1.0;
  19950. break;
  19951. }
  19952. return photometricScale;
  19953. };
  19954. /**
  19955. * Reorder the light in the scene according to their defined priority.
  19956. * @ignore Internal Use Only
  19957. */
  19958. Light.prototype._reorderLightsInScene = function () {
  19959. var scene = this.getScene();
  19960. if (this._renderPriority != 0) {
  19961. scene.requireLightSorting = true;
  19962. }
  19963. this.getScene().sortLightsByPriority();
  19964. };
  19965. //lightmapMode Consts
  19966. Light._LIGHTMAP_DEFAULT = 0;
  19967. Light._LIGHTMAP_SPECULAR = 1;
  19968. Light._LIGHTMAP_SHADOWSONLY = 2;
  19969. // Intensity Mode Consts
  19970. Light._INTENSITYMODE_AUTOMATIC = 0;
  19971. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19972. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19973. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19974. Light._INTENSITYMODE_LUMINANCE = 4;
  19975. // Light types ids const.
  19976. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19977. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19978. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19979. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19980. __decorate([
  19981. BABYLON.serializeAsColor3()
  19982. ], Light.prototype, "diffuse", void 0);
  19983. __decorate([
  19984. BABYLON.serializeAsColor3()
  19985. ], Light.prototype, "specular", void 0);
  19986. __decorate([
  19987. BABYLON.serialize()
  19988. ], Light.prototype, "intensity", void 0);
  19989. __decorate([
  19990. BABYLON.serialize()
  19991. ], Light.prototype, "range", void 0);
  19992. __decorate([
  19993. BABYLON.serialize()
  19994. ], Light.prototype, "intensityMode", null);
  19995. __decorate([
  19996. BABYLON.serialize()
  19997. ], Light.prototype, "radius", null);
  19998. __decorate([
  19999. BABYLON.serialize()
  20000. ], Light.prototype, "_renderPriority", void 0);
  20001. __decorate([
  20002. BABYLON.expandToProperty("_reorderLightsInScene")
  20003. ], Light.prototype, "renderPriority", void 0);
  20004. __decorate([
  20005. BABYLON.serialize()
  20006. ], Light.prototype, "shadowEnabled", void 0);
  20007. __decorate([
  20008. BABYLON.serialize("excludeWithLayerMask")
  20009. ], Light.prototype, "_excludeWithLayerMask", void 0);
  20010. __decorate([
  20011. BABYLON.serialize("includeOnlyWithLayerMask")
  20012. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  20013. __decorate([
  20014. BABYLON.serialize("lightmapMode")
  20015. ], Light.prototype, "_lightmapMode", void 0);
  20016. return Light;
  20017. }(BABYLON.Node));
  20018. BABYLON.Light = Light;
  20019. })(BABYLON || (BABYLON = {}));
  20020. //# sourceMappingURL=babylon.light.js.map
  20021. "use strict";
  20022. var BABYLON;
  20023. (function (BABYLON) {
  20024. var Camera = /** @class */ (function (_super) {
  20025. __extends(Camera, _super);
  20026. function Camera(name, position, scene) {
  20027. var _this = _super.call(this, name, scene) || this;
  20028. /**
  20029. * The vector the camera should consider as up.
  20030. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  20031. */
  20032. _this.upVector = BABYLON.Vector3.Up();
  20033. _this.orthoLeft = null;
  20034. _this.orthoRight = null;
  20035. _this.orthoBottom = null;
  20036. _this.orthoTop = null;
  20037. /**
  20038. * FOV is set in Radians. (default is 0.8)
  20039. */
  20040. _this.fov = 0.8;
  20041. _this.minZ = 1;
  20042. _this.maxZ = 10000.0;
  20043. _this.inertia = 0.9;
  20044. _this.mode = Camera.PERSPECTIVE_CAMERA;
  20045. _this.isIntermediate = false;
  20046. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  20047. /**
  20048. * Restricts the camera to viewing objects with the same layerMask.
  20049. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  20050. */
  20051. _this.layerMask = 0x0FFFFFFF;
  20052. /**
  20053. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  20054. */
  20055. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  20056. // Camera rig members
  20057. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  20058. _this._rigCameras = new Array();
  20059. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  20060. _this._skipRendering = false;
  20061. _this.customRenderTargets = new Array();
  20062. // Observables
  20063. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  20064. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  20065. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  20066. _this.onRestoreStateObservable = new BABYLON.Observable();
  20067. // Cache
  20068. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  20069. _this._projectionMatrix = new BABYLON.Matrix();
  20070. _this._doNotComputeProjectionMatrix = false;
  20071. _this._postProcesses = new Array();
  20072. _this._transformMatrix = BABYLON.Matrix.Zero();
  20073. _this._activeMeshes = new BABYLON.SmartArray(256);
  20074. _this._globalPosition = BABYLON.Vector3.Zero();
  20075. _this._refreshFrustumPlanes = true;
  20076. _this.getScene().addCamera(_this);
  20077. if (!_this.getScene().activeCamera) {
  20078. _this.getScene().activeCamera = _this;
  20079. }
  20080. _this.position = position;
  20081. return _this;
  20082. }
  20083. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  20084. get: function () {
  20085. return Camera._PERSPECTIVE_CAMERA;
  20086. },
  20087. enumerable: true,
  20088. configurable: true
  20089. });
  20090. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  20091. get: function () {
  20092. return Camera._ORTHOGRAPHIC_CAMERA;
  20093. },
  20094. enumerable: true,
  20095. configurable: true
  20096. });
  20097. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  20098. /**
  20099. * This is the default FOV mode for perspective cameras.
  20100. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  20101. *
  20102. */
  20103. get: function () {
  20104. return Camera._FOVMODE_VERTICAL_FIXED;
  20105. },
  20106. enumerable: true,
  20107. configurable: true
  20108. });
  20109. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  20110. /**
  20111. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  20112. *
  20113. */
  20114. get: function () {
  20115. return Camera._FOVMODE_HORIZONTAL_FIXED;
  20116. },
  20117. enumerable: true,
  20118. configurable: true
  20119. });
  20120. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  20121. get: function () {
  20122. return Camera._RIG_MODE_NONE;
  20123. },
  20124. enumerable: true,
  20125. configurable: true
  20126. });
  20127. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  20128. get: function () {
  20129. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  20130. },
  20131. enumerable: true,
  20132. configurable: true
  20133. });
  20134. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  20135. get: function () {
  20136. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  20137. },
  20138. enumerable: true,
  20139. configurable: true
  20140. });
  20141. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  20142. get: function () {
  20143. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20144. },
  20145. enumerable: true,
  20146. configurable: true
  20147. });
  20148. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  20149. get: function () {
  20150. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  20151. },
  20152. enumerable: true,
  20153. configurable: true
  20154. });
  20155. Object.defineProperty(Camera, "RIG_MODE_VR", {
  20156. get: function () {
  20157. return Camera._RIG_MODE_VR;
  20158. },
  20159. enumerable: true,
  20160. configurable: true
  20161. });
  20162. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  20163. get: function () {
  20164. return Camera._RIG_MODE_WEBVR;
  20165. },
  20166. enumerable: true,
  20167. configurable: true
  20168. });
  20169. /**
  20170. * Store current camera state (fov, position, etc..)
  20171. */
  20172. Camera.prototype.storeState = function () {
  20173. this._stateStored = true;
  20174. this._storedFov = this.fov;
  20175. return this;
  20176. };
  20177. /**
  20178. * Restores the camera state values if it has been stored. You must call storeState() first
  20179. */
  20180. Camera.prototype._restoreStateValues = function () {
  20181. if (!this._stateStored) {
  20182. return false;
  20183. }
  20184. this.fov = this._storedFov;
  20185. return true;
  20186. };
  20187. /**
  20188. * Restored camera state. You must call storeState() first
  20189. */
  20190. Camera.prototype.restoreState = function () {
  20191. if (this._restoreStateValues()) {
  20192. this.onRestoreStateObservable.notifyObservers(this);
  20193. return true;
  20194. }
  20195. return false;
  20196. };
  20197. Camera.prototype.getClassName = function () {
  20198. return "Camera";
  20199. };
  20200. /**
  20201. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20202. */
  20203. Camera.prototype.toString = function (fullDetails) {
  20204. var ret = "Name: " + this.name;
  20205. ret += ", type: " + this.getClassName();
  20206. if (this.animations) {
  20207. for (var i = 0; i < this.animations.length; i++) {
  20208. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20209. }
  20210. }
  20211. if (fullDetails) {
  20212. }
  20213. return ret;
  20214. };
  20215. Object.defineProperty(Camera.prototype, "globalPosition", {
  20216. get: function () {
  20217. return this._globalPosition;
  20218. },
  20219. enumerable: true,
  20220. configurable: true
  20221. });
  20222. Camera.prototype.getActiveMeshes = function () {
  20223. return this._activeMeshes;
  20224. };
  20225. Camera.prototype.isActiveMesh = function (mesh) {
  20226. return (this._activeMeshes.indexOf(mesh) !== -1);
  20227. };
  20228. //Cache
  20229. Camera.prototype._initCache = function () {
  20230. _super.prototype._initCache.call(this);
  20231. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20232. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20233. this._cache.mode = undefined;
  20234. this._cache.minZ = undefined;
  20235. this._cache.maxZ = undefined;
  20236. this._cache.fov = undefined;
  20237. this._cache.fovMode = undefined;
  20238. this._cache.aspectRatio = undefined;
  20239. this._cache.orthoLeft = undefined;
  20240. this._cache.orthoRight = undefined;
  20241. this._cache.orthoBottom = undefined;
  20242. this._cache.orthoTop = undefined;
  20243. this._cache.renderWidth = undefined;
  20244. this._cache.renderHeight = undefined;
  20245. };
  20246. Camera.prototype._updateCache = function (ignoreParentClass) {
  20247. if (!ignoreParentClass) {
  20248. _super.prototype._updateCache.call(this);
  20249. }
  20250. this._cache.position.copyFrom(this.position);
  20251. this._cache.upVector.copyFrom(this.upVector);
  20252. };
  20253. // Synchronized
  20254. Camera.prototype._isSynchronized = function () {
  20255. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20256. };
  20257. Camera.prototype._isSynchronizedViewMatrix = function () {
  20258. if (!_super.prototype._isSynchronized.call(this))
  20259. return false;
  20260. return this._cache.position.equals(this.position)
  20261. && this._cache.upVector.equals(this.upVector)
  20262. && this.isSynchronizedWithParent();
  20263. };
  20264. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20265. var check = this._cache.mode === this.mode
  20266. && this._cache.minZ === this.minZ
  20267. && this._cache.maxZ === this.maxZ;
  20268. if (!check) {
  20269. return false;
  20270. }
  20271. var engine = this.getEngine();
  20272. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20273. check = this._cache.fov === this.fov
  20274. && this._cache.fovMode === this.fovMode
  20275. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20276. }
  20277. else {
  20278. check = this._cache.orthoLeft === this.orthoLeft
  20279. && this._cache.orthoRight === this.orthoRight
  20280. && this._cache.orthoBottom === this.orthoBottom
  20281. && this._cache.orthoTop === this.orthoTop
  20282. && this._cache.renderWidth === engine.getRenderWidth()
  20283. && this._cache.renderHeight === engine.getRenderHeight();
  20284. }
  20285. return check;
  20286. };
  20287. // Controls
  20288. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20289. };
  20290. Camera.prototype.detachControl = function (element) {
  20291. };
  20292. Camera.prototype.update = function () {
  20293. this._checkInputs();
  20294. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20295. this._updateRigCameras();
  20296. }
  20297. };
  20298. Camera.prototype._checkInputs = function () {
  20299. this.onAfterCheckInputsObservable.notifyObservers(this);
  20300. };
  20301. Object.defineProperty(Camera.prototype, "rigCameras", {
  20302. get: function () {
  20303. return this._rigCameras;
  20304. },
  20305. enumerable: true,
  20306. configurable: true
  20307. });
  20308. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20309. get: function () {
  20310. return this._rigPostProcess;
  20311. },
  20312. enumerable: true,
  20313. configurable: true
  20314. });
  20315. /**
  20316. * Internal, gets the first post proces.
  20317. * @returns the first post process to be run on this camera.
  20318. */
  20319. Camera.prototype._getFirstPostProcess = function () {
  20320. for (var pp in this._postProcesses) {
  20321. if (this._postProcesses[pp] !== null) {
  20322. return this._postProcesses[pp];
  20323. }
  20324. }
  20325. return null;
  20326. };
  20327. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20328. // invalidate framebuffer
  20329. var firstPostProcess = this._getFirstPostProcess();
  20330. if (firstPostProcess) {
  20331. firstPostProcess.markTextureDirty();
  20332. }
  20333. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20334. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20335. var cam = this._rigCameras[i];
  20336. var rigPostProcess = cam._rigPostProcess;
  20337. // for VR rig, there does not have to be a post process
  20338. if (rigPostProcess) {
  20339. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20340. if (isPass) {
  20341. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20342. cam.isIntermediate = this._postProcesses.length === 0;
  20343. }
  20344. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20345. rigPostProcess.markTextureDirty();
  20346. }
  20347. else {
  20348. cam._postProcesses = this._postProcesses.slice(0);
  20349. }
  20350. }
  20351. };
  20352. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20353. if (insertAt === void 0) { insertAt = null; }
  20354. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20355. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20356. return 0;
  20357. }
  20358. if (insertAt == null || insertAt < 0) {
  20359. this._postProcesses.push(postProcess);
  20360. }
  20361. else if (this._postProcesses[insertAt] === null) {
  20362. this._postProcesses[insertAt] = postProcess;
  20363. }
  20364. else {
  20365. this._postProcesses.splice(insertAt, 0, postProcess);
  20366. }
  20367. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20368. return this._postProcesses.indexOf(postProcess);
  20369. };
  20370. Camera.prototype.detachPostProcess = function (postProcess) {
  20371. var idx = this._postProcesses.indexOf(postProcess);
  20372. if (idx !== -1) {
  20373. this._postProcesses[idx] = null;
  20374. }
  20375. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20376. };
  20377. Camera.prototype.getWorldMatrix = function () {
  20378. if (!this._worldMatrix) {
  20379. this._worldMatrix = BABYLON.Matrix.Identity();
  20380. }
  20381. var viewMatrix = this.getViewMatrix();
  20382. viewMatrix.invertToRef(this._worldMatrix);
  20383. return this._worldMatrix;
  20384. };
  20385. Camera.prototype._getViewMatrix = function () {
  20386. return BABYLON.Matrix.Identity();
  20387. };
  20388. Camera.prototype.getViewMatrix = function (force) {
  20389. if (!force && this._isSynchronizedViewMatrix()) {
  20390. return this._computedViewMatrix;
  20391. }
  20392. this.updateCache();
  20393. this._computedViewMatrix = this._getViewMatrix();
  20394. this._currentRenderId = this.getScene().getRenderId();
  20395. this._refreshFrustumPlanes = true;
  20396. if (!this.parent || !this.parent.getWorldMatrix) {
  20397. this._globalPosition.copyFrom(this.position);
  20398. }
  20399. else {
  20400. if (!this._worldMatrix) {
  20401. this._worldMatrix = BABYLON.Matrix.Identity();
  20402. }
  20403. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20404. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20405. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20406. this._computedViewMatrix.invert();
  20407. this._markSyncedWithParent();
  20408. }
  20409. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20410. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20411. }
  20412. this.onViewMatrixChangedObservable.notifyObservers(this);
  20413. return this._computedViewMatrix;
  20414. };
  20415. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20416. this._doNotComputeProjectionMatrix = true;
  20417. if (projection !== undefined) {
  20418. this._projectionMatrix = projection;
  20419. }
  20420. };
  20421. ;
  20422. Camera.prototype.unfreezeProjectionMatrix = function () {
  20423. this._doNotComputeProjectionMatrix = false;
  20424. };
  20425. ;
  20426. Camera.prototype.getProjectionMatrix = function (force) {
  20427. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20428. return this._projectionMatrix;
  20429. }
  20430. // Cache
  20431. this._cache.mode = this.mode;
  20432. this._cache.minZ = this.minZ;
  20433. this._cache.maxZ = this.maxZ;
  20434. // Matrix
  20435. this._refreshFrustumPlanes = true;
  20436. var engine = this.getEngine();
  20437. var scene = this.getScene();
  20438. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20439. this._cache.fov = this.fov;
  20440. this._cache.fovMode = this.fovMode;
  20441. this._cache.aspectRatio = engine.getAspectRatio(this);
  20442. if (this.minZ <= 0) {
  20443. this.minZ = 0.1;
  20444. }
  20445. if (scene.useRightHandedSystem) {
  20446. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20447. }
  20448. else {
  20449. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20450. }
  20451. }
  20452. else {
  20453. var halfWidth = engine.getRenderWidth() / 2.0;
  20454. var halfHeight = engine.getRenderHeight() / 2.0;
  20455. if (scene.useRightHandedSystem) {
  20456. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20457. }
  20458. else {
  20459. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20460. }
  20461. this._cache.orthoLeft = this.orthoLeft;
  20462. this._cache.orthoRight = this.orthoRight;
  20463. this._cache.orthoBottom = this.orthoBottom;
  20464. this._cache.orthoTop = this.orthoTop;
  20465. this._cache.renderWidth = engine.getRenderWidth();
  20466. this._cache.renderHeight = engine.getRenderHeight();
  20467. }
  20468. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20469. return this._projectionMatrix;
  20470. };
  20471. Camera.prototype.getTranformationMatrix = function () {
  20472. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20473. return this._transformMatrix;
  20474. };
  20475. Camera.prototype.updateFrustumPlanes = function () {
  20476. if (!this._refreshFrustumPlanes) {
  20477. return;
  20478. }
  20479. this.getTranformationMatrix();
  20480. if (!this._frustumPlanes) {
  20481. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20482. }
  20483. else {
  20484. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20485. }
  20486. this._refreshFrustumPlanes = false;
  20487. };
  20488. Camera.prototype.isInFrustum = function (target) {
  20489. this.updateFrustumPlanes();
  20490. return target.isInFrustum(this._frustumPlanes);
  20491. };
  20492. Camera.prototype.isCompletelyInFrustum = function (target) {
  20493. this.updateFrustumPlanes();
  20494. return target.isCompletelyInFrustum(this._frustumPlanes);
  20495. };
  20496. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20497. if (length === void 0) { length = 100; }
  20498. if (!transform) {
  20499. transform = this.getWorldMatrix();
  20500. }
  20501. if (!origin) {
  20502. origin = this.position;
  20503. }
  20504. var forward = new BABYLON.Vector3(0, 0, 1);
  20505. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20506. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20507. return new BABYLON.Ray(origin, direction, length);
  20508. };
  20509. /**
  20510. * Releases resources associated with this node.
  20511. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20512. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20513. */
  20514. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20515. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20516. // Observables
  20517. this.onViewMatrixChangedObservable.clear();
  20518. this.onProjectionMatrixChangedObservable.clear();
  20519. this.onAfterCheckInputsObservable.clear();
  20520. this.onRestoreStateObservable.clear();
  20521. // Inputs
  20522. if (this.inputs) {
  20523. this.inputs.clear();
  20524. }
  20525. // Animations
  20526. this.getScene().stopAnimation(this);
  20527. // Remove from scene
  20528. this.getScene().removeCamera(this);
  20529. while (this._rigCameras.length > 0) {
  20530. var camera = this._rigCameras.pop();
  20531. if (camera) {
  20532. camera.dispose();
  20533. }
  20534. }
  20535. // Postprocesses
  20536. if (this._rigPostProcess) {
  20537. this._rigPostProcess.dispose(this);
  20538. this._rigPostProcess = null;
  20539. this._postProcesses = [];
  20540. }
  20541. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20542. this._rigPostProcess = null;
  20543. this._postProcesses = [];
  20544. }
  20545. else {
  20546. var i = this._postProcesses.length;
  20547. while (--i >= 0) {
  20548. var postProcess = this._postProcesses[i];
  20549. if (postProcess) {
  20550. postProcess.dispose(this);
  20551. }
  20552. }
  20553. }
  20554. // Render targets
  20555. var i = this.customRenderTargets.length;
  20556. while (--i >= 0) {
  20557. this.customRenderTargets[i].dispose();
  20558. }
  20559. this.customRenderTargets = [];
  20560. // Active Meshes
  20561. this._activeMeshes.dispose();
  20562. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20563. };
  20564. Object.defineProperty(Camera.prototype, "leftCamera", {
  20565. // ---- Camera rigs section ----
  20566. get: function () {
  20567. if (this._rigCameras.length < 1) {
  20568. return null;
  20569. }
  20570. return this._rigCameras[0];
  20571. },
  20572. enumerable: true,
  20573. configurable: true
  20574. });
  20575. Object.defineProperty(Camera.prototype, "rightCamera", {
  20576. get: function () {
  20577. if (this._rigCameras.length < 2) {
  20578. return null;
  20579. }
  20580. return this._rigCameras[1];
  20581. },
  20582. enumerable: true,
  20583. configurable: true
  20584. });
  20585. Camera.prototype.getLeftTarget = function () {
  20586. if (this._rigCameras.length < 1) {
  20587. return null;
  20588. }
  20589. return this._rigCameras[0].getTarget();
  20590. };
  20591. Camera.prototype.getRightTarget = function () {
  20592. if (this._rigCameras.length < 2) {
  20593. return null;
  20594. }
  20595. return this._rigCameras[1].getTarget();
  20596. };
  20597. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20598. if (this.cameraRigMode === mode) {
  20599. return;
  20600. }
  20601. while (this._rigCameras.length > 0) {
  20602. var camera = this._rigCameras.pop();
  20603. if (camera) {
  20604. camera.dispose();
  20605. }
  20606. }
  20607. this.cameraRigMode = mode;
  20608. this._cameraRigParams = {};
  20609. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20610. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20611. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20612. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20613. // create the rig cameras, unless none
  20614. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20615. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20616. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20617. if (leftCamera && rightCamera) {
  20618. this._rigCameras.push(leftCamera);
  20619. this._rigCameras.push(rightCamera);
  20620. }
  20621. }
  20622. switch (this.cameraRigMode) {
  20623. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20624. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20625. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20626. break;
  20627. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20628. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20629. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20630. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20631. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20632. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20633. break;
  20634. case Camera.RIG_MODE_VR:
  20635. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20636. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20637. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20638. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20639. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20640. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20641. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20642. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20643. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20644. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20645. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20646. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20647. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20648. if (metrics.compensateDistortion) {
  20649. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20650. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20651. }
  20652. break;
  20653. case Camera.RIG_MODE_WEBVR:
  20654. if (rigParams.vrDisplay) {
  20655. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20656. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20657. //Left eye
  20658. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20659. this._rigCameras[0].setCameraRigParameter("left", true);
  20660. //leaving this for future reference
  20661. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20662. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20663. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20664. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20665. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20666. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20667. this._rigCameras[0].parent = this;
  20668. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20669. //Right eye
  20670. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20671. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20672. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20673. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20674. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20675. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20676. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20677. this._rigCameras[1].parent = this;
  20678. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20679. if (Camera.UseAlternateWebVRRendering) {
  20680. this._rigCameras[1]._skipRendering = true;
  20681. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20682. }
  20683. }
  20684. break;
  20685. }
  20686. this._cascadePostProcessesToRigCams();
  20687. this.update();
  20688. };
  20689. Camera.prototype._getVRProjectionMatrix = function () {
  20690. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20691. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20692. return this._projectionMatrix;
  20693. };
  20694. Camera.prototype._updateCameraRotationMatrix = function () {
  20695. //Here for WebVR
  20696. };
  20697. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20698. //Here for WebVR
  20699. };
  20700. /**
  20701. * This function MUST be overwritten by the different WebVR cameras available.
  20702. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20703. */
  20704. Camera.prototype._getWebVRProjectionMatrix = function () {
  20705. return BABYLON.Matrix.Identity();
  20706. };
  20707. /**
  20708. * This function MUST be overwritten by the different WebVR cameras available.
  20709. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20710. */
  20711. Camera.prototype._getWebVRViewMatrix = function () {
  20712. return BABYLON.Matrix.Identity();
  20713. };
  20714. Camera.prototype.setCameraRigParameter = function (name, value) {
  20715. if (!this._cameraRigParams) {
  20716. this._cameraRigParams = {};
  20717. }
  20718. this._cameraRigParams[name] = value;
  20719. //provisionnally:
  20720. if (name === "interaxialDistance") {
  20721. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20722. }
  20723. };
  20724. /**
  20725. * needs to be overridden by children so sub has required properties to be copied
  20726. */
  20727. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20728. return null;
  20729. };
  20730. /**
  20731. * May need to be overridden by children
  20732. */
  20733. Camera.prototype._updateRigCameras = function () {
  20734. for (var i = 0; i < this._rigCameras.length; i++) {
  20735. this._rigCameras[i].minZ = this.minZ;
  20736. this._rigCameras[i].maxZ = this.maxZ;
  20737. this._rigCameras[i].fov = this.fov;
  20738. }
  20739. // only update viewport when ANAGLYPH
  20740. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20741. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20742. }
  20743. };
  20744. Camera.prototype._setupInputs = function () {
  20745. };
  20746. Camera.prototype.serialize = function () {
  20747. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20748. // Type
  20749. serializationObject.type = this.getClassName();
  20750. // Parent
  20751. if (this.parent) {
  20752. serializationObject.parentId = this.parent.id;
  20753. }
  20754. if (this.inputs) {
  20755. this.inputs.serialize(serializationObject);
  20756. }
  20757. // Animations
  20758. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20759. serializationObject.ranges = this.serializeAnimationRanges();
  20760. return serializationObject;
  20761. };
  20762. Camera.prototype.clone = function (name) {
  20763. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20764. };
  20765. Camera.prototype.getDirection = function (localAxis) {
  20766. var result = BABYLON.Vector3.Zero();
  20767. this.getDirectionToRef(localAxis, result);
  20768. return result;
  20769. };
  20770. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20771. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20772. };
  20773. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20774. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20775. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20776. switch (type) {
  20777. case "ArcRotateCamera":
  20778. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20779. case "DeviceOrientationCamera":
  20780. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20781. case "FollowCamera":
  20782. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20783. case "ArcFollowCamera":
  20784. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20785. case "GamepadCamera":
  20786. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20787. case "TouchCamera":
  20788. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20789. case "VirtualJoysticksCamera":
  20790. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20791. case "WebVRFreeCamera":
  20792. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20793. case "WebVRGamepadCamera":
  20794. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20795. case "VRDeviceOrientationFreeCamera":
  20796. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20797. case "VRDeviceOrientationGamepadCamera":
  20798. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20799. case "AnaglyphArcRotateCamera":
  20800. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20801. case "AnaglyphFreeCamera":
  20802. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20803. case "AnaglyphGamepadCamera":
  20804. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20805. case "AnaglyphUniversalCamera":
  20806. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20807. case "StereoscopicArcRotateCamera":
  20808. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20809. case "StereoscopicFreeCamera":
  20810. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20811. case "StereoscopicGamepadCamera":
  20812. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20813. case "StereoscopicUniversalCamera":
  20814. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20815. case "FreeCamera":// Forcing Universal here
  20816. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20817. default:// Universal Camera is the default value
  20818. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20819. }
  20820. };
  20821. Camera.prototype.computeWorldMatrix = function () {
  20822. return this.getWorldMatrix();
  20823. };
  20824. Camera.Parse = function (parsedCamera, scene) {
  20825. var type = parsedCamera.type;
  20826. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20827. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20828. // Parent
  20829. if (parsedCamera.parentId) {
  20830. camera._waitingParentId = parsedCamera.parentId;
  20831. }
  20832. //If camera has an input manager, let it parse inputs settings
  20833. if (camera.inputs) {
  20834. camera.inputs.parse(parsedCamera);
  20835. camera._setupInputs();
  20836. }
  20837. if (camera.setPosition) {
  20838. camera.position.copyFromFloats(0, 0, 0);
  20839. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20840. }
  20841. // Target
  20842. if (parsedCamera.target) {
  20843. if (camera.setTarget) {
  20844. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20845. }
  20846. }
  20847. // Apply 3d rig, when found
  20848. if (parsedCamera.cameraRigMode) {
  20849. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20850. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20851. }
  20852. // Animations
  20853. if (parsedCamera.animations) {
  20854. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20855. var parsedAnimation = parsedCamera.animations[animationIndex];
  20856. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20857. }
  20858. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20859. }
  20860. if (parsedCamera.autoAnimate) {
  20861. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20862. }
  20863. return camera;
  20864. };
  20865. // Statics
  20866. Camera._PERSPECTIVE_CAMERA = 0;
  20867. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20868. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20869. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20870. Camera._RIG_MODE_NONE = 0;
  20871. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20872. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20873. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20874. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20875. Camera._RIG_MODE_VR = 20;
  20876. Camera._RIG_MODE_WEBVR = 21;
  20877. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20878. Camera.UseAlternateWebVRRendering = false;
  20879. __decorate([
  20880. BABYLON.serializeAsVector3()
  20881. ], Camera.prototype, "position", void 0);
  20882. __decorate([
  20883. BABYLON.serializeAsVector3()
  20884. ], Camera.prototype, "upVector", void 0);
  20885. __decorate([
  20886. BABYLON.serialize()
  20887. ], Camera.prototype, "orthoLeft", void 0);
  20888. __decorate([
  20889. BABYLON.serialize()
  20890. ], Camera.prototype, "orthoRight", void 0);
  20891. __decorate([
  20892. BABYLON.serialize()
  20893. ], Camera.prototype, "orthoBottom", void 0);
  20894. __decorate([
  20895. BABYLON.serialize()
  20896. ], Camera.prototype, "orthoTop", void 0);
  20897. __decorate([
  20898. BABYLON.serialize()
  20899. ], Camera.prototype, "fov", void 0);
  20900. __decorate([
  20901. BABYLON.serialize()
  20902. ], Camera.prototype, "minZ", void 0);
  20903. __decorate([
  20904. BABYLON.serialize()
  20905. ], Camera.prototype, "maxZ", void 0);
  20906. __decorate([
  20907. BABYLON.serialize()
  20908. ], Camera.prototype, "inertia", void 0);
  20909. __decorate([
  20910. BABYLON.serialize()
  20911. ], Camera.prototype, "mode", void 0);
  20912. __decorate([
  20913. BABYLON.serialize()
  20914. ], Camera.prototype, "layerMask", void 0);
  20915. __decorate([
  20916. BABYLON.serialize()
  20917. ], Camera.prototype, "fovMode", void 0);
  20918. __decorate([
  20919. BABYLON.serialize()
  20920. ], Camera.prototype, "cameraRigMode", void 0);
  20921. __decorate([
  20922. BABYLON.serialize()
  20923. ], Camera.prototype, "interaxialDistance", void 0);
  20924. __decorate([
  20925. BABYLON.serialize()
  20926. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20927. return Camera;
  20928. }(BABYLON.Node));
  20929. BABYLON.Camera = Camera;
  20930. })(BABYLON || (BABYLON = {}));
  20931. //# sourceMappingURL=babylon.camera.js.map
  20932. "use strict";
  20933. var BABYLON;
  20934. (function (BABYLON) {
  20935. var RenderingManager = /** @class */ (function () {
  20936. function RenderingManager(scene) {
  20937. this._renderingGroups = new Array();
  20938. this._autoClearDepthStencil = {};
  20939. this._customOpaqueSortCompareFn = {};
  20940. this._customAlphaTestSortCompareFn = {};
  20941. this._customTransparentSortCompareFn = {};
  20942. this._renderinGroupInfo = null;
  20943. this._scene = scene;
  20944. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20945. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20946. }
  20947. }
  20948. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20949. if (depth === void 0) { depth = true; }
  20950. if (stencil === void 0) { stencil = true; }
  20951. if (this._depthStencilBufferAlreadyCleaned) {
  20952. return;
  20953. }
  20954. this._scene.getEngine().clear(null, false, depth, stencil);
  20955. this._depthStencilBufferAlreadyCleaned = true;
  20956. };
  20957. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20958. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20959. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20960. var info = null;
  20961. if (observable) {
  20962. if (!this._renderinGroupInfo) {
  20963. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20964. }
  20965. info = this._renderinGroupInfo;
  20966. info.scene = this._scene;
  20967. info.camera = this._scene.activeCamera;
  20968. }
  20969. // Dispatch sprites
  20970. if (renderSprites) {
  20971. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20972. var manager = this._scene.spriteManagers[index];
  20973. this.dispatchSprites(manager);
  20974. }
  20975. }
  20976. // Render
  20977. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20978. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20979. var renderingGroup = this._renderingGroups[index];
  20980. if (!renderingGroup && !observable)
  20981. continue;
  20982. var renderingGroupMask = 0;
  20983. // Fire PRECLEAR stage
  20984. if (observable && info) {
  20985. renderingGroupMask = Math.pow(2, index);
  20986. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20987. info.renderingGroupId = index;
  20988. observable.notifyObservers(info, renderingGroupMask);
  20989. }
  20990. // Clear depth/stencil if needed
  20991. if (RenderingManager.AUTOCLEAR) {
  20992. var autoClear = this._autoClearDepthStencil[index];
  20993. if (autoClear && autoClear.autoClear) {
  20994. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20995. }
  20996. }
  20997. if (observable && info) {
  20998. // Fire PREOPAQUE stage
  20999. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  21000. observable.notifyObservers(info, renderingGroupMask);
  21001. // Fire PRETRANSPARENT stage
  21002. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  21003. observable.notifyObservers(info, renderingGroupMask);
  21004. }
  21005. if (renderingGroup)
  21006. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  21007. // Fire POSTTRANSPARENT stage
  21008. if (observable && info) {
  21009. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  21010. observable.notifyObservers(info, renderingGroupMask);
  21011. }
  21012. }
  21013. };
  21014. RenderingManager.prototype.reset = function () {
  21015. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21016. var renderingGroup = this._renderingGroups[index];
  21017. if (renderingGroup) {
  21018. renderingGroup.prepare();
  21019. }
  21020. }
  21021. };
  21022. RenderingManager.prototype.dispose = function () {
  21023. this.freeRenderingGroups();
  21024. this._renderingGroups.length = 0;
  21025. };
  21026. /**
  21027. * Clear the info related to rendering groups preventing retention points during dispose.
  21028. */
  21029. RenderingManager.prototype.freeRenderingGroups = function () {
  21030. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21031. var renderingGroup = this._renderingGroups[index];
  21032. if (renderingGroup) {
  21033. renderingGroup.dispose();
  21034. }
  21035. }
  21036. };
  21037. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  21038. if (this._renderingGroups[renderingGroupId] === undefined) {
  21039. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  21040. }
  21041. };
  21042. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  21043. var renderingGroupId = spriteManager.renderingGroupId || 0;
  21044. this._prepareRenderingGroup(renderingGroupId);
  21045. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  21046. };
  21047. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  21048. var renderingGroupId = particleSystem.renderingGroupId || 0;
  21049. this._prepareRenderingGroup(renderingGroupId);
  21050. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  21051. };
  21052. /**
  21053. * @param subMesh The submesh to dispatch
  21054. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21055. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21056. */
  21057. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  21058. if (mesh === undefined) {
  21059. mesh = subMesh.getMesh();
  21060. }
  21061. var renderingGroupId = mesh.renderingGroupId || 0;
  21062. this._prepareRenderingGroup(renderingGroupId);
  21063. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  21064. };
  21065. /**
  21066. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21067. * This allowed control for front to back rendering or reversly depending of the special needs.
  21068. *
  21069. * @param renderingGroupId The rendering group id corresponding to its index
  21070. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21071. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21072. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21073. */
  21074. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21075. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21076. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21077. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21078. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  21079. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  21080. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  21081. if (this._renderingGroups[renderingGroupId]) {
  21082. var group = this._renderingGroups[renderingGroupId];
  21083. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  21084. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  21085. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  21086. }
  21087. };
  21088. /**
  21089. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21090. *
  21091. * @param renderingGroupId The rendering group id corresponding to its index
  21092. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21093. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21094. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21095. */
  21096. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21097. if (depth === void 0) { depth = true; }
  21098. if (stencil === void 0) { stencil = true; }
  21099. this._autoClearDepthStencil[renderingGroupId] = {
  21100. autoClear: autoClearDepthStencil,
  21101. depth: depth,
  21102. stencil: stencil
  21103. };
  21104. };
  21105. /**
  21106. * The max id used for rendering groups (not included)
  21107. */
  21108. RenderingManager.MAX_RENDERINGGROUPS = 4;
  21109. /**
  21110. * The min id used for rendering groups (included)
  21111. */
  21112. RenderingManager.MIN_RENDERINGGROUPS = 0;
  21113. /**
  21114. * Used to globally prevent autoclearing scenes.
  21115. */
  21116. RenderingManager.AUTOCLEAR = true;
  21117. return RenderingManager;
  21118. }());
  21119. BABYLON.RenderingManager = RenderingManager;
  21120. })(BABYLON || (BABYLON = {}));
  21121. //# sourceMappingURL=babylon.renderingManager.js.map
  21122. "use strict";
  21123. var BABYLON;
  21124. (function (BABYLON) {
  21125. var RenderingGroup = /** @class */ (function () {
  21126. /**
  21127. * Creates a new rendering group.
  21128. * @param index The rendering group index
  21129. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  21130. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  21131. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  21132. */
  21133. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21134. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21135. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21136. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21137. this.index = index;
  21138. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  21139. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  21140. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  21141. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  21142. this._particleSystems = new BABYLON.SmartArray(256);
  21143. this._spriteManagers = new BABYLON.SmartArray(256);
  21144. this._edgesRenderers = new BABYLON.SmartArray(16);
  21145. this._scene = scene;
  21146. this.opaqueSortCompareFn = opaqueSortCompareFn;
  21147. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  21148. this.transparentSortCompareFn = transparentSortCompareFn;
  21149. }
  21150. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  21151. /**
  21152. * Set the opaque sort comparison function.
  21153. * If null the sub meshes will be render in the order they were created
  21154. */
  21155. set: function (value) {
  21156. this._opaqueSortCompareFn = value;
  21157. if (value) {
  21158. this._renderOpaque = this.renderOpaqueSorted;
  21159. }
  21160. else {
  21161. this._renderOpaque = RenderingGroup.renderUnsorted;
  21162. }
  21163. },
  21164. enumerable: true,
  21165. configurable: true
  21166. });
  21167. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  21168. /**
  21169. * Set the alpha test sort comparison function.
  21170. * If null the sub meshes will be render in the order they were created
  21171. */
  21172. set: function (value) {
  21173. this._alphaTestSortCompareFn = value;
  21174. if (value) {
  21175. this._renderAlphaTest = this.renderAlphaTestSorted;
  21176. }
  21177. else {
  21178. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  21179. }
  21180. },
  21181. enumerable: true,
  21182. configurable: true
  21183. });
  21184. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21185. /**
  21186. * Set the transparent sort comparison function.
  21187. * If null the sub meshes will be render in the order they were created
  21188. */
  21189. set: function (value) {
  21190. if (value) {
  21191. this._transparentSortCompareFn = value;
  21192. }
  21193. else {
  21194. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21195. }
  21196. this._renderTransparent = this.renderTransparentSorted;
  21197. },
  21198. enumerable: true,
  21199. configurable: true
  21200. });
  21201. /**
  21202. * Render all the sub meshes contained in the group.
  21203. * @param customRenderFunction Used to override the default render behaviour of the group.
  21204. * @returns true if rendered some submeshes.
  21205. */
  21206. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21207. if (customRenderFunction) {
  21208. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21209. return;
  21210. }
  21211. var engine = this._scene.getEngine();
  21212. // Depth only
  21213. if (this._depthOnlySubMeshes.length !== 0) {
  21214. engine.setColorWrite(false);
  21215. this._renderAlphaTest(this._depthOnlySubMeshes);
  21216. engine.setColorWrite(true);
  21217. }
  21218. // Opaque
  21219. if (this._opaqueSubMeshes.length !== 0) {
  21220. this._renderOpaque(this._opaqueSubMeshes);
  21221. }
  21222. // Alpha test
  21223. if (this._alphaTestSubMeshes.length !== 0) {
  21224. this._renderAlphaTest(this._alphaTestSubMeshes);
  21225. }
  21226. var stencilState = engine.getStencilBuffer();
  21227. engine.setStencilBuffer(false);
  21228. // Sprites
  21229. if (renderSprites) {
  21230. this._renderSprites();
  21231. }
  21232. // Particles
  21233. if (renderParticles) {
  21234. this._renderParticles(activeMeshes);
  21235. }
  21236. if (this.onBeforeTransparentRendering) {
  21237. this.onBeforeTransparentRendering();
  21238. }
  21239. // Transparent
  21240. if (this._transparentSubMeshes.length !== 0) {
  21241. this._renderTransparent(this._transparentSubMeshes);
  21242. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21243. }
  21244. // Set back stencil to false in case it changes before the edge renderer.
  21245. engine.setStencilBuffer(false);
  21246. // Edges
  21247. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21248. this._edgesRenderers.data[edgesRendererIndex].render();
  21249. }
  21250. // Restore Stencil state.
  21251. engine.setStencilBuffer(stencilState);
  21252. };
  21253. /**
  21254. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21255. * @param subMeshes The submeshes to render
  21256. */
  21257. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21258. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21259. };
  21260. /**
  21261. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21262. * @param subMeshes The submeshes to render
  21263. */
  21264. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21265. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21266. };
  21267. /**
  21268. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21269. * @param subMeshes The submeshes to render
  21270. */
  21271. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21272. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21273. };
  21274. /**
  21275. * Renders the submeshes in a specified order.
  21276. * @param subMeshes The submeshes to sort before render
  21277. * @param sortCompareFn The comparison function use to sort
  21278. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21279. * @param transparent Specifies to activate blending if true
  21280. */
  21281. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21282. var subIndex = 0;
  21283. var subMesh;
  21284. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21285. for (; subIndex < subMeshes.length; subIndex++) {
  21286. subMesh = subMeshes.data[subIndex];
  21287. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21288. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21289. }
  21290. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21291. if (sortCompareFn) {
  21292. sortedArray.sort(sortCompareFn);
  21293. }
  21294. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21295. subMesh = sortedArray[subIndex];
  21296. if (transparent) {
  21297. var material = subMesh.getMaterial();
  21298. if (material && material.needDepthPrePass) {
  21299. var engine = material.getScene().getEngine();
  21300. engine.setColorWrite(false);
  21301. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21302. subMesh.render(false);
  21303. engine.setColorWrite(true);
  21304. }
  21305. }
  21306. subMesh.render(transparent);
  21307. }
  21308. };
  21309. /**
  21310. * Renders the submeshes in the order they were dispatched (no sort applied).
  21311. * @param subMeshes The submeshes to render
  21312. */
  21313. RenderingGroup.renderUnsorted = function (subMeshes) {
  21314. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21315. var submesh = subMeshes.data[subIndex];
  21316. submesh.render(false);
  21317. }
  21318. };
  21319. /**
  21320. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21321. * are rendered back to front if in the same alpha index.
  21322. *
  21323. * @param a The first submesh
  21324. * @param b The second submesh
  21325. * @returns The result of the comparison
  21326. */
  21327. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21328. // Alpha index first
  21329. if (a._alphaIndex > b._alphaIndex) {
  21330. return 1;
  21331. }
  21332. if (a._alphaIndex < b._alphaIndex) {
  21333. return -1;
  21334. }
  21335. // Then distance to camera
  21336. return RenderingGroup.backToFrontSortCompare(a, b);
  21337. };
  21338. /**
  21339. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21340. * are rendered back to front.
  21341. *
  21342. * @param a The first submesh
  21343. * @param b The second submesh
  21344. * @returns The result of the comparison
  21345. */
  21346. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21347. // Then distance to camera
  21348. if (a._distanceToCamera < b._distanceToCamera) {
  21349. return 1;
  21350. }
  21351. if (a._distanceToCamera > b._distanceToCamera) {
  21352. return -1;
  21353. }
  21354. return 0;
  21355. };
  21356. /**
  21357. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21358. * are rendered front to back (prevent overdraw).
  21359. *
  21360. * @param a The first submesh
  21361. * @param b The second submesh
  21362. * @returns The result of the comparison
  21363. */
  21364. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21365. // Then distance to camera
  21366. if (a._distanceToCamera < b._distanceToCamera) {
  21367. return -1;
  21368. }
  21369. if (a._distanceToCamera > b._distanceToCamera) {
  21370. return 1;
  21371. }
  21372. return 0;
  21373. };
  21374. /**
  21375. * Resets the different lists of submeshes to prepare a new frame.
  21376. */
  21377. RenderingGroup.prototype.prepare = function () {
  21378. this._opaqueSubMeshes.reset();
  21379. this._transparentSubMeshes.reset();
  21380. this._alphaTestSubMeshes.reset();
  21381. this._depthOnlySubMeshes.reset();
  21382. this._particleSystems.reset();
  21383. this._spriteManagers.reset();
  21384. this._edgesRenderers.reset();
  21385. };
  21386. RenderingGroup.prototype.dispose = function () {
  21387. this._opaqueSubMeshes.dispose();
  21388. this._transparentSubMeshes.dispose();
  21389. this._alphaTestSubMeshes.dispose();
  21390. this._depthOnlySubMeshes.dispose();
  21391. this._particleSystems.dispose();
  21392. this._spriteManagers.dispose();
  21393. this._edgesRenderers.dispose();
  21394. };
  21395. /**
  21396. * Inserts the submesh in its correct queue depending on its material.
  21397. * @param subMesh The submesh to dispatch
  21398. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21399. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21400. */
  21401. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21402. // Get mesh and materials if not provided
  21403. if (mesh === undefined) {
  21404. mesh = subMesh.getMesh();
  21405. }
  21406. if (material === undefined) {
  21407. material = subMesh.getMaterial();
  21408. }
  21409. if (material === null || material === undefined) {
  21410. return;
  21411. }
  21412. if (material.needAlphaBlendingForMesh(mesh)) {
  21413. this._transparentSubMeshes.push(subMesh);
  21414. }
  21415. else if (material.needAlphaTesting()) {
  21416. if (material.needDepthPrePass) {
  21417. this._depthOnlySubMeshes.push(subMesh);
  21418. }
  21419. this._alphaTestSubMeshes.push(subMesh);
  21420. }
  21421. else {
  21422. if (material.needDepthPrePass) {
  21423. this._depthOnlySubMeshes.push(subMesh);
  21424. }
  21425. this._opaqueSubMeshes.push(subMesh); // Opaque
  21426. }
  21427. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21428. this._edgesRenderers.push(mesh._edgesRenderer);
  21429. }
  21430. };
  21431. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21432. this._spriteManagers.push(spriteManager);
  21433. };
  21434. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21435. this._particleSystems.push(particleSystem);
  21436. };
  21437. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21438. if (this._particleSystems.length === 0) {
  21439. return;
  21440. }
  21441. // Particles
  21442. var activeCamera = this._scene.activeCamera;
  21443. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21444. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21445. var particleSystem = this._particleSystems.data[particleIndex];
  21446. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21447. continue;
  21448. }
  21449. var emitter = particleSystem.emitter;
  21450. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21451. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21452. }
  21453. }
  21454. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21455. };
  21456. RenderingGroup.prototype._renderSprites = function () {
  21457. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21458. return;
  21459. }
  21460. // Sprites
  21461. var activeCamera = this._scene.activeCamera;
  21462. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21463. for (var id = 0; id < this._spriteManagers.length; id++) {
  21464. var spriteManager = this._spriteManagers.data[id];
  21465. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21466. spriteManager.render();
  21467. }
  21468. }
  21469. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21470. };
  21471. return RenderingGroup;
  21472. }());
  21473. BABYLON.RenderingGroup = RenderingGroup;
  21474. })(BABYLON || (BABYLON = {}));
  21475. //# sourceMappingURL=babylon.renderingGroup.js.map
  21476. "use strict";
  21477. var BABYLON;
  21478. (function (BABYLON) {
  21479. var ClickInfo = /** @class */ (function () {
  21480. function ClickInfo() {
  21481. this._singleClick = false;
  21482. this._doubleClick = false;
  21483. this._hasSwiped = false;
  21484. this._ignore = false;
  21485. }
  21486. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21487. get: function () {
  21488. return this._singleClick;
  21489. },
  21490. set: function (b) {
  21491. this._singleClick = b;
  21492. },
  21493. enumerable: true,
  21494. configurable: true
  21495. });
  21496. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21497. get: function () {
  21498. return this._doubleClick;
  21499. },
  21500. set: function (b) {
  21501. this._doubleClick = b;
  21502. },
  21503. enumerable: true,
  21504. configurable: true
  21505. });
  21506. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21507. get: function () {
  21508. return this._hasSwiped;
  21509. },
  21510. set: function (b) {
  21511. this._hasSwiped = b;
  21512. },
  21513. enumerable: true,
  21514. configurable: true
  21515. });
  21516. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21517. get: function () {
  21518. return this._ignore;
  21519. },
  21520. set: function (b) {
  21521. this._ignore = b;
  21522. },
  21523. enumerable: true,
  21524. configurable: true
  21525. });
  21526. return ClickInfo;
  21527. }());
  21528. /**
  21529. * This class is used by the onRenderingGroupObservable
  21530. */
  21531. var RenderingGroupInfo = /** @class */ (function () {
  21532. function RenderingGroupInfo() {
  21533. }
  21534. /**
  21535. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21536. * This stage will be fired no matter what
  21537. */
  21538. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21539. /**
  21540. * Called before opaque object are rendered.
  21541. * This stage will be fired only if there's 3D Opaque content to render
  21542. */
  21543. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21544. /**
  21545. * Called after the opaque objects are rendered and before the transparent ones
  21546. * This stage will be fired only if there's 3D transparent content to render
  21547. */
  21548. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21549. /**
  21550. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21551. * This stage will be fired no matter what
  21552. */
  21553. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21554. return RenderingGroupInfo;
  21555. }());
  21556. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21557. /**
  21558. * Represents a scene to be rendered by the engine.
  21559. * @see http://doc.babylonjs.com/page.php?p=21911
  21560. */
  21561. var Scene = /** @class */ (function () {
  21562. /**
  21563. * @constructor
  21564. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21565. */
  21566. function Scene(engine) {
  21567. // Members
  21568. this.autoClear = true;
  21569. this.autoClearDepthAndStencil = true;
  21570. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21571. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21572. this._forceWireframe = false;
  21573. this._forcePointsCloud = false;
  21574. this.forceShowBoundingBoxes = false;
  21575. this.animationsEnabled = true;
  21576. this.useConstantAnimationDeltaTime = false;
  21577. this.constantlyUpdateMeshUnderPointer = false;
  21578. this.hoverCursor = "pointer";
  21579. this.defaultCursor = "";
  21580. /**
  21581. * This is used to call preventDefault() on pointer down
  21582. * in order to block unwanted artifacts like system double clicks
  21583. */
  21584. this.preventDefaultOnPointerDown = true;
  21585. // Metadata
  21586. this.metadata = null;
  21587. /**
  21588. * An event triggered when the scene is disposed.
  21589. * @type {BABYLON.Observable}
  21590. */
  21591. this.onDisposeObservable = new BABYLON.Observable();
  21592. this._onDisposeObserver = null;
  21593. /**
  21594. * An event triggered before rendering the scene (right after animations and physics)
  21595. * @type {BABYLON.Observable}
  21596. */
  21597. this.onBeforeRenderObservable = new BABYLON.Observable();
  21598. this._onBeforeRenderObserver = null;
  21599. /**
  21600. * An event triggered after rendering the scene
  21601. * @type {BABYLON.Observable}
  21602. */
  21603. this.onAfterRenderObservable = new BABYLON.Observable();
  21604. this._onAfterRenderObserver = null;
  21605. /**
  21606. * An event triggered before animating the scene
  21607. * @type {BABYLON.Observable}
  21608. */
  21609. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21610. /**
  21611. * An event triggered after animations processing
  21612. * @type {BABYLON.Observable}
  21613. */
  21614. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21615. /**
  21616. * An event triggered before draw calls are ready to be sent
  21617. * @type {BABYLON.Observable}
  21618. */
  21619. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21620. /**
  21621. * An event triggered after draw calls have been sent
  21622. * @type {BABYLON.Observable}
  21623. */
  21624. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21625. /**
  21626. * An event triggered when physic simulation is about to be run
  21627. * @type {BABYLON.Observable}
  21628. */
  21629. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21630. /**
  21631. * An event triggered when physic simulation has been done
  21632. * @type {BABYLON.Observable}
  21633. */
  21634. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21635. /**
  21636. * An event triggered when the scene is ready
  21637. * @type {BABYLON.Observable}
  21638. */
  21639. this.onReadyObservable = new BABYLON.Observable();
  21640. /**
  21641. * An event triggered before rendering a camera
  21642. * @type {BABYLON.Observable}
  21643. */
  21644. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21645. this._onBeforeCameraRenderObserver = null;
  21646. /**
  21647. * An event triggered after rendering a camera
  21648. * @type {BABYLON.Observable}
  21649. */
  21650. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21651. this._onAfterCameraRenderObserver = null;
  21652. /**
  21653. * An event triggered when active meshes evaluation is about to start
  21654. * @type {BABYLON.Observable}
  21655. */
  21656. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21657. /**
  21658. * An event triggered when active meshes evaluation is done
  21659. * @type {BABYLON.Observable}
  21660. */
  21661. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21662. /**
  21663. * An event triggered when particles rendering is about to start
  21664. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21665. * @type {BABYLON.Observable}
  21666. */
  21667. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21668. /**
  21669. * An event triggered when particles rendering is done
  21670. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21671. * @type {BABYLON.Observable}
  21672. */
  21673. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21674. /**
  21675. * An event triggered when sprites rendering is about to start
  21676. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21677. * @type {BABYLON.Observable}
  21678. */
  21679. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21680. /**
  21681. * An event triggered when sprites rendering is done
  21682. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21683. * @type {BABYLON.Observable}
  21684. */
  21685. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21686. /**
  21687. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21688. * @type {BABYLON.Observable}
  21689. */
  21690. this.onDataLoadedObservable = new BABYLON.Observable();
  21691. /**
  21692. * An event triggered when a camera is created
  21693. * @type {BABYLON.Observable}
  21694. */
  21695. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21696. /**
  21697. * An event triggered when a camera is removed
  21698. * @type {BABYLON.Observable}
  21699. */
  21700. this.onCameraRemovedObservable = new BABYLON.Observable();
  21701. /**
  21702. * An event triggered when a light is created
  21703. * @type {BABYLON.Observable}
  21704. */
  21705. this.onNewLightAddedObservable = new BABYLON.Observable();
  21706. /**
  21707. * An event triggered when a light is removed
  21708. * @type {BABYLON.Observable}
  21709. */
  21710. this.onLightRemovedObservable = new BABYLON.Observable();
  21711. /**
  21712. * An event triggered when a geometry is created
  21713. * @type {BABYLON.Observable}
  21714. */
  21715. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21716. /**
  21717. * An event triggered when a geometry is removed
  21718. * @type {BABYLON.Observable}
  21719. */
  21720. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21721. /**
  21722. * An event triggered when a transform node is created
  21723. * @type {BABYLON.Observable}
  21724. */
  21725. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21726. /**
  21727. * An event triggered when a transform node is removed
  21728. * @type {BABYLON.Observable}
  21729. */
  21730. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21731. /**
  21732. * An event triggered when a mesh is created
  21733. * @type {BABYLON.Observable}
  21734. */
  21735. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21736. /**
  21737. * An event triggered when a mesh is removed
  21738. * @type {BABYLON.Observable}
  21739. */
  21740. this.onMeshRemovedObservable = new BABYLON.Observable();
  21741. /**
  21742. * An event triggered when render targets are about to be rendered
  21743. * Can happen multiple times per frame.
  21744. * @type {BABYLON.Observable}
  21745. */
  21746. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21747. /**
  21748. * An event triggered when render targets were rendered.
  21749. * Can happen multiple times per frame.
  21750. * @type {BABYLON.Observable}
  21751. */
  21752. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21753. /**
  21754. * An event triggered before calculating deterministic simulation step
  21755. * @type {BABYLON.Observable}
  21756. */
  21757. this.onBeforeStepObservable = new BABYLON.Observable();
  21758. /**
  21759. * An event triggered after calculating deterministic simulation step
  21760. * @type {BABYLON.Observable}
  21761. */
  21762. this.onAfterStepObservable = new BABYLON.Observable();
  21763. /**
  21764. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21765. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21766. * 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)
  21767. */
  21768. this.onRenderingGroupObservable = new BABYLON.Observable();
  21769. // Animations
  21770. this.animations = [];
  21771. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  21772. /**
  21773. * 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).
  21774. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21775. */
  21776. this.onPrePointerObservable = new BABYLON.Observable();
  21777. /**
  21778. * Observable event triggered each time an input event is received from the rendering canvas
  21779. */
  21780. this.onPointerObservable = new BABYLON.Observable();
  21781. this._meshPickProceed = false;
  21782. this._currentPickResult = null;
  21783. this._previousPickResult = null;
  21784. this._totalPointersPressed = 0;
  21785. this._doubleClickOccured = false;
  21786. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21787. this.cameraToUseForPointers = null;
  21788. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21789. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21790. this._startingPointerTime = 0;
  21791. this._previousStartingPointerTime = 0;
  21792. // Deterministic lockstep
  21793. this._timeAccumulator = 0;
  21794. this._currentStepId = 0;
  21795. this._currentInternalStep = 0;
  21796. // Keyboard
  21797. /**
  21798. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21799. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21800. */
  21801. this.onPreKeyboardObservable = new BABYLON.Observable();
  21802. /**
  21803. * Observable event triggered each time an keyboard event is received from the hosting window
  21804. */
  21805. this.onKeyboardObservable = new BABYLON.Observable();
  21806. // Coordinate system
  21807. /**
  21808. * use right-handed coordinate system on this scene.
  21809. * @type {boolean}
  21810. */
  21811. this._useRightHandedSystem = false;
  21812. // Fog
  21813. this._fogEnabled = true;
  21814. this._fogMode = Scene.FOGMODE_NONE;
  21815. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21816. this.fogDensity = 0.1;
  21817. this.fogStart = 0;
  21818. this.fogEnd = 1000.0;
  21819. // Lights
  21820. /**
  21821. * is shadow enabled on this scene.
  21822. * @type {boolean}
  21823. */
  21824. this._shadowsEnabled = true;
  21825. /**
  21826. * is light enabled on this scene.
  21827. * @type {boolean}
  21828. */
  21829. this._lightsEnabled = true;
  21830. /**
  21831. * All of the lights added to this scene.
  21832. * @see BABYLON.Light
  21833. * @type {BABYLON.Light[]}
  21834. */
  21835. this.lights = new Array();
  21836. // Cameras
  21837. /** All of the cameras added to this scene. */
  21838. this.cameras = new Array();
  21839. /** All of the active cameras added to this scene. */
  21840. this.activeCameras = new Array();
  21841. // Meshes
  21842. /**
  21843. * All of the tranform nodes added to this scene.
  21844. * @see BABYLON.TransformNode
  21845. * @type {BABYLON.TransformNode[]}
  21846. */
  21847. this.transformNodes = new Array();
  21848. /**
  21849. * All of the (abstract) meshes added to this scene.
  21850. * @see BABYLON.AbstractMesh
  21851. * @type {BABYLON.AbstractMesh[]}
  21852. */
  21853. this.meshes = new Array();
  21854. /**
  21855. * All of the animation groups added to this scene.
  21856. * @see BABYLON.AnimationGroup
  21857. * @type {BABYLON.AnimationGroup[]}
  21858. */
  21859. this.animationGroups = new Array();
  21860. // Geometries
  21861. this._geometries = new Array();
  21862. this.materials = new Array();
  21863. this.multiMaterials = new Array();
  21864. // Textures
  21865. this._texturesEnabled = true;
  21866. this.textures = new Array();
  21867. // Particles
  21868. this.particlesEnabled = true;
  21869. this.particleSystems = new Array();
  21870. // Sprites
  21871. this.spritesEnabled = true;
  21872. this.spriteManagers = new Array();
  21873. /**
  21874. * The list of layers (background and foreground) of the scene.
  21875. */
  21876. this.layers = new Array();
  21877. /**
  21878. * The list of effect layers (highlights/glow) contained in the scene.
  21879. */
  21880. this.effectLayers = new Array();
  21881. // Skeletons
  21882. this._skeletonsEnabled = true;
  21883. this.skeletons = new Array();
  21884. // Morph targets
  21885. this.morphTargetManagers = new Array();
  21886. // Lens flares
  21887. this.lensFlaresEnabled = true;
  21888. this.lensFlareSystems = new Array();
  21889. // Collisions
  21890. this.collisionsEnabled = true;
  21891. /** Defines the gravity applied to this scene */
  21892. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21893. // Postprocesses
  21894. this.postProcesses = new Array();
  21895. this.postProcessesEnabled = true;
  21896. // Customs render targets
  21897. this.renderTargetsEnabled = true;
  21898. this.dumpNextRenderTargets = false;
  21899. this.customRenderTargets = new Array();
  21900. // Imported meshes
  21901. this.importedMeshesFiles = new Array();
  21902. // Probes
  21903. this.probesEnabled = true;
  21904. this.reflectionProbes = new Array();
  21905. this._actionManagers = new Array();
  21906. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21907. // Procedural textures
  21908. this.proceduralTexturesEnabled = true;
  21909. this._proceduralTextures = new Array();
  21910. this.soundTracks = new Array();
  21911. this._audioEnabled = true;
  21912. this._headphone = false;
  21913. // Performance counters
  21914. this._totalVertices = new BABYLON.PerfCounter();
  21915. this._activeIndices = new BABYLON.PerfCounter();
  21916. this._activeParticles = new BABYLON.PerfCounter();
  21917. this._activeBones = new BABYLON.PerfCounter();
  21918. this._animationTime = 0;
  21919. this.animationTimeScale = 1;
  21920. this._renderId = 0;
  21921. this._executeWhenReadyTimeoutId = -1;
  21922. this._intermediateRendering = false;
  21923. this._viewUpdateFlag = -1;
  21924. this._projectionUpdateFlag = -1;
  21925. this._alternateViewUpdateFlag = -1;
  21926. this._alternateProjectionUpdateFlag = -1;
  21927. this._toBeDisposed = new BABYLON.SmartArray(256);
  21928. this._activeRequests = new Array();
  21929. this._pendingData = new Array();
  21930. this._isDisposed = false;
  21931. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21932. this._activeMeshes = new BABYLON.SmartArray(256);
  21933. this._processedMaterials = new BABYLON.SmartArray(256);
  21934. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21935. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21936. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21937. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21938. this._activeAnimatables = new Array();
  21939. this._transformMatrix = BABYLON.Matrix.Zero();
  21940. this._useAlternateCameraConfiguration = false;
  21941. this._alternateRendering = false;
  21942. this.requireLightSorting = false;
  21943. this._depthRenderer = {};
  21944. this._activeMeshesFrozen = false;
  21945. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21946. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21947. this._engine.scenes.push(this);
  21948. this._uid = null;
  21949. this._renderingManager = new BABYLON.RenderingManager(this);
  21950. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21951. if (BABYLON.OutlineRenderer) {
  21952. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21953. }
  21954. if (BABYLON.Tools.IsWindowObjectExist()) {
  21955. this.attachControl();
  21956. }
  21957. //simplification queue
  21958. if (BABYLON.SimplificationQueue) {
  21959. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21960. }
  21961. //collision coordinator initialization. For now legacy per default.
  21962. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21963. // Uniform Buffer
  21964. this._createUbo();
  21965. // Default Image processing definition.
  21966. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21967. }
  21968. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21969. /** The fog is deactivated */
  21970. get: function () {
  21971. return Scene._FOGMODE_NONE;
  21972. },
  21973. enumerable: true,
  21974. configurable: true
  21975. });
  21976. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21977. /** The fog density is following an exponential function */
  21978. get: function () {
  21979. return Scene._FOGMODE_EXP;
  21980. },
  21981. enumerable: true,
  21982. configurable: true
  21983. });
  21984. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21985. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21986. get: function () {
  21987. return Scene._FOGMODE_EXP2;
  21988. },
  21989. enumerable: true,
  21990. configurable: true
  21991. });
  21992. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21993. /** The fog density is following a linear function. */
  21994. get: function () {
  21995. return Scene._FOGMODE_LINEAR;
  21996. },
  21997. enumerable: true,
  21998. configurable: true
  21999. });
  22000. Object.defineProperty(Scene.prototype, "environmentTexture", {
  22001. /**
  22002. * Texture used in all pbr material as the reflection texture.
  22003. * As in the majority of the scene they are the same (exception for multi room and so on),
  22004. * this is easier to reference from here than from all the materials.
  22005. */
  22006. get: function () {
  22007. return this._environmentTexture;
  22008. },
  22009. /**
  22010. * Texture used in all pbr material as the reflection texture.
  22011. * As in the majority of the scene they are the same (exception for multi room and so on),
  22012. * this is easier to set here than in all the materials.
  22013. */
  22014. set: function (value) {
  22015. if (this._environmentTexture === value) {
  22016. return;
  22017. }
  22018. this._environmentTexture = value;
  22019. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22020. },
  22021. enumerable: true,
  22022. configurable: true
  22023. });
  22024. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  22025. /**
  22026. * Default image processing configuration used either in the rendering
  22027. * Forward main pass or through the imageProcessingPostProcess if present.
  22028. * As in the majority of the scene they are the same (exception for multi camera),
  22029. * this is easier to reference from here than from all the materials and post process.
  22030. *
  22031. * No setter as we it is a shared configuration, you can set the values instead.
  22032. */
  22033. get: function () {
  22034. return this._imageProcessingConfiguration;
  22035. },
  22036. enumerable: true,
  22037. configurable: true
  22038. });
  22039. Object.defineProperty(Scene.prototype, "forceWireframe", {
  22040. get: function () {
  22041. return this._forceWireframe;
  22042. },
  22043. set: function (value) {
  22044. if (this._forceWireframe === value) {
  22045. return;
  22046. }
  22047. this._forceWireframe = value;
  22048. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22049. },
  22050. enumerable: true,
  22051. configurable: true
  22052. });
  22053. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  22054. get: function () {
  22055. return this._forcePointsCloud;
  22056. },
  22057. set: function (value) {
  22058. if (this._forcePointsCloud === value) {
  22059. return;
  22060. }
  22061. this._forcePointsCloud = value;
  22062. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22063. },
  22064. enumerable: true,
  22065. configurable: true
  22066. });
  22067. Object.defineProperty(Scene.prototype, "onDispose", {
  22068. /** A function to be executed when this scene is disposed. */
  22069. set: function (callback) {
  22070. if (this._onDisposeObserver) {
  22071. this.onDisposeObservable.remove(this._onDisposeObserver);
  22072. }
  22073. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22074. },
  22075. enumerable: true,
  22076. configurable: true
  22077. });
  22078. Object.defineProperty(Scene.prototype, "beforeRender", {
  22079. /** A function to be executed before rendering this scene */
  22080. set: function (callback) {
  22081. if (this._onBeforeRenderObserver) {
  22082. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22083. }
  22084. if (callback) {
  22085. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22086. }
  22087. },
  22088. enumerable: true,
  22089. configurable: true
  22090. });
  22091. Object.defineProperty(Scene.prototype, "afterRender", {
  22092. /** A function to be executed after rendering this scene */
  22093. set: function (callback) {
  22094. if (this._onAfterRenderObserver) {
  22095. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22096. }
  22097. if (callback) {
  22098. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22099. }
  22100. },
  22101. enumerable: true,
  22102. configurable: true
  22103. });
  22104. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  22105. set: function (callback) {
  22106. if (this._onBeforeCameraRenderObserver) {
  22107. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  22108. }
  22109. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  22110. },
  22111. enumerable: true,
  22112. configurable: true
  22113. });
  22114. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  22115. set: function (callback) {
  22116. if (this._onAfterCameraRenderObserver) {
  22117. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  22118. }
  22119. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  22120. },
  22121. enumerable: true,
  22122. configurable: true
  22123. });
  22124. Object.defineProperty(Scene.prototype, "gamepadManager", {
  22125. get: function () {
  22126. if (!this._gamepadManager) {
  22127. this._gamepadManager = new BABYLON.GamepadManager(this);
  22128. }
  22129. return this._gamepadManager;
  22130. },
  22131. enumerable: true,
  22132. configurable: true
  22133. });
  22134. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  22135. get: function () {
  22136. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  22137. },
  22138. enumerable: true,
  22139. configurable: true
  22140. });
  22141. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  22142. get: function () {
  22143. return this._useRightHandedSystem;
  22144. },
  22145. set: function (value) {
  22146. if (this._useRightHandedSystem === value) {
  22147. return;
  22148. }
  22149. this._useRightHandedSystem = value;
  22150. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22151. },
  22152. enumerable: true,
  22153. configurable: true
  22154. });
  22155. Scene.prototype.setStepId = function (newStepId) {
  22156. this._currentStepId = newStepId;
  22157. };
  22158. ;
  22159. Scene.prototype.getStepId = function () {
  22160. return this._currentStepId;
  22161. };
  22162. ;
  22163. Scene.prototype.getInternalStep = function () {
  22164. return this._currentInternalStep;
  22165. };
  22166. ;
  22167. Object.defineProperty(Scene.prototype, "fogEnabled", {
  22168. get: function () {
  22169. return this._fogEnabled;
  22170. },
  22171. /**
  22172. * is fog enabled on this scene.
  22173. */
  22174. set: function (value) {
  22175. if (this._fogEnabled === value) {
  22176. return;
  22177. }
  22178. this._fogEnabled = value;
  22179. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22180. },
  22181. enumerable: true,
  22182. configurable: true
  22183. });
  22184. Object.defineProperty(Scene.prototype, "fogMode", {
  22185. get: function () {
  22186. return this._fogMode;
  22187. },
  22188. set: function (value) {
  22189. if (this._fogMode === value) {
  22190. return;
  22191. }
  22192. this._fogMode = value;
  22193. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22194. },
  22195. enumerable: true,
  22196. configurable: true
  22197. });
  22198. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  22199. get: function () {
  22200. return this._shadowsEnabled;
  22201. },
  22202. set: function (value) {
  22203. if (this._shadowsEnabled === value) {
  22204. return;
  22205. }
  22206. this._shadowsEnabled = value;
  22207. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22208. },
  22209. enumerable: true,
  22210. configurable: true
  22211. });
  22212. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22213. get: function () {
  22214. return this._lightsEnabled;
  22215. },
  22216. set: function (value) {
  22217. if (this._lightsEnabled === value) {
  22218. return;
  22219. }
  22220. this._lightsEnabled = value;
  22221. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22222. },
  22223. enumerable: true,
  22224. configurable: true
  22225. });
  22226. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22227. /** The default material used on meshes when no material is affected */
  22228. get: function () {
  22229. if (!this._defaultMaterial) {
  22230. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22231. }
  22232. return this._defaultMaterial;
  22233. },
  22234. /** The default material used on meshes when no material is affected */
  22235. set: function (value) {
  22236. this._defaultMaterial = value;
  22237. },
  22238. enumerable: true,
  22239. configurable: true
  22240. });
  22241. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22242. get: function () {
  22243. return this._texturesEnabled;
  22244. },
  22245. set: function (value) {
  22246. if (this._texturesEnabled === value) {
  22247. return;
  22248. }
  22249. this._texturesEnabled = value;
  22250. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22251. },
  22252. enumerable: true,
  22253. configurable: true
  22254. });
  22255. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22256. get: function () {
  22257. return this._skeletonsEnabled;
  22258. },
  22259. set: function (value) {
  22260. if (this._skeletonsEnabled === value) {
  22261. return;
  22262. }
  22263. this._skeletonsEnabled = value;
  22264. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22265. },
  22266. enumerable: true,
  22267. configurable: true
  22268. });
  22269. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22270. get: function () {
  22271. if (!this._postProcessRenderPipelineManager) {
  22272. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22273. }
  22274. return this._postProcessRenderPipelineManager;
  22275. },
  22276. enumerable: true,
  22277. configurable: true
  22278. });
  22279. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22280. get: function () {
  22281. if (!this._mainSoundTrack) {
  22282. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22283. }
  22284. return this._mainSoundTrack;
  22285. },
  22286. enumerable: true,
  22287. configurable: true
  22288. });
  22289. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22290. get: function () {
  22291. return this._alternateRendering;
  22292. },
  22293. enumerable: true,
  22294. configurable: true
  22295. });
  22296. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22297. get: function () {
  22298. return this._frustumPlanes;
  22299. },
  22300. enumerable: true,
  22301. configurable: true
  22302. });
  22303. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22304. /**
  22305. * Gets the current geometry buffer associated to the scene.
  22306. */
  22307. get: function () {
  22308. return this._geometryBufferRenderer;
  22309. },
  22310. /**
  22311. * Sets the current geometry buffer for the scene.
  22312. */
  22313. set: function (geometryBufferRenderer) {
  22314. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22315. this._geometryBufferRenderer = geometryBufferRenderer;
  22316. }
  22317. },
  22318. enumerable: true,
  22319. configurable: true
  22320. });
  22321. Object.defineProperty(Scene.prototype, "debugLayer", {
  22322. // Properties
  22323. get: function () {
  22324. if (!this._debugLayer) {
  22325. this._debugLayer = new BABYLON.DebugLayer(this);
  22326. }
  22327. return this._debugLayer;
  22328. },
  22329. enumerable: true,
  22330. configurable: true
  22331. });
  22332. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22333. get: function () {
  22334. return this._workerCollisions;
  22335. },
  22336. set: function (enabled) {
  22337. if (!BABYLON.CollisionCoordinatorLegacy) {
  22338. return;
  22339. }
  22340. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22341. this._workerCollisions = enabled;
  22342. if (this.collisionCoordinator) {
  22343. this.collisionCoordinator.destroy();
  22344. }
  22345. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22346. this.collisionCoordinator.init(this);
  22347. },
  22348. enumerable: true,
  22349. configurable: true
  22350. });
  22351. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22352. get: function () {
  22353. return this._selectionOctree;
  22354. },
  22355. enumerable: true,
  22356. configurable: true
  22357. });
  22358. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22359. /**
  22360. * The mesh that is currently under the pointer.
  22361. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22362. */
  22363. get: function () {
  22364. return this._pointerOverMesh;
  22365. },
  22366. enumerable: true,
  22367. configurable: true
  22368. });
  22369. Object.defineProperty(Scene.prototype, "pointerX", {
  22370. /**
  22371. * Current on-screen X position of the pointer
  22372. * @return {number} X position of the pointer
  22373. */
  22374. get: function () {
  22375. return this._pointerX;
  22376. },
  22377. enumerable: true,
  22378. configurable: true
  22379. });
  22380. Object.defineProperty(Scene.prototype, "pointerY", {
  22381. /**
  22382. * Current on-screen Y position of the pointer
  22383. * @return {number} Y position of the pointer
  22384. */
  22385. get: function () {
  22386. return this._pointerY;
  22387. },
  22388. enumerable: true,
  22389. configurable: true
  22390. });
  22391. Scene.prototype.getCachedMaterial = function () {
  22392. return this._cachedMaterial;
  22393. };
  22394. Scene.prototype.getCachedEffect = function () {
  22395. return this._cachedEffect;
  22396. };
  22397. Scene.prototype.getCachedVisibility = function () {
  22398. return this._cachedVisibility;
  22399. };
  22400. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22401. if (visibility === void 0) { visibility = 1; }
  22402. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22403. };
  22404. Scene.prototype.getBoundingBoxRenderer = function () {
  22405. if (!this._boundingBoxRenderer) {
  22406. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22407. }
  22408. return this._boundingBoxRenderer;
  22409. };
  22410. Scene.prototype.getOutlineRenderer = function () {
  22411. return this._outlineRenderer;
  22412. };
  22413. Scene.prototype.getEngine = function () {
  22414. return this._engine;
  22415. };
  22416. Scene.prototype.getTotalVertices = function () {
  22417. return this._totalVertices.current;
  22418. };
  22419. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22420. get: function () {
  22421. return this._totalVertices;
  22422. },
  22423. enumerable: true,
  22424. configurable: true
  22425. });
  22426. Scene.prototype.getActiveIndices = function () {
  22427. return this._activeIndices.current;
  22428. };
  22429. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22430. get: function () {
  22431. return this._activeIndices;
  22432. },
  22433. enumerable: true,
  22434. configurable: true
  22435. });
  22436. Scene.prototype.getActiveParticles = function () {
  22437. return this._activeParticles.current;
  22438. };
  22439. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22440. get: function () {
  22441. return this._activeParticles;
  22442. },
  22443. enumerable: true,
  22444. configurable: true
  22445. });
  22446. Scene.prototype.getActiveBones = function () {
  22447. return this._activeBones.current;
  22448. };
  22449. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22450. get: function () {
  22451. return this._activeBones;
  22452. },
  22453. enumerable: true,
  22454. configurable: true
  22455. });
  22456. // Stats
  22457. Scene.prototype.getInterFramePerfCounter = function () {
  22458. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22459. return 0;
  22460. };
  22461. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22462. get: function () {
  22463. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22464. return null;
  22465. },
  22466. enumerable: true,
  22467. configurable: true
  22468. });
  22469. Scene.prototype.getLastFrameDuration = function () {
  22470. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22471. return 0;
  22472. };
  22473. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22474. get: function () {
  22475. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22476. return null;
  22477. },
  22478. enumerable: true,
  22479. configurable: true
  22480. });
  22481. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22482. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22483. return 0;
  22484. };
  22485. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22486. get: function () {
  22487. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22488. return null;
  22489. },
  22490. enumerable: true,
  22491. configurable: true
  22492. });
  22493. Scene.prototype.getActiveMeshes = function () {
  22494. return this._activeMeshes;
  22495. };
  22496. Scene.prototype.getRenderTargetsDuration = function () {
  22497. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22498. return 0;
  22499. };
  22500. Scene.prototype.getRenderDuration = function () {
  22501. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22502. return 0;
  22503. };
  22504. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22505. get: function () {
  22506. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22507. return null;
  22508. },
  22509. enumerable: true,
  22510. configurable: true
  22511. });
  22512. Scene.prototype.getParticlesDuration = function () {
  22513. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22514. return 0;
  22515. };
  22516. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22517. get: function () {
  22518. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22519. return null;
  22520. },
  22521. enumerable: true,
  22522. configurable: true
  22523. });
  22524. Scene.prototype.getSpritesDuration = function () {
  22525. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22526. return 0;
  22527. };
  22528. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22529. get: function () {
  22530. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22531. return null;
  22532. },
  22533. enumerable: true,
  22534. configurable: true
  22535. });
  22536. Scene.prototype.getAnimationRatio = function () {
  22537. return this._animationRatio;
  22538. };
  22539. Scene.prototype.getRenderId = function () {
  22540. return this._renderId;
  22541. };
  22542. Scene.prototype.incrementRenderId = function () {
  22543. this._renderId++;
  22544. };
  22545. Scene.prototype._updatePointerPosition = function (evt) {
  22546. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22547. if (!canvasRect) {
  22548. return;
  22549. }
  22550. this._pointerX = evt.clientX - canvasRect.left;
  22551. this._pointerY = evt.clientY - canvasRect.top;
  22552. this._unTranslatedPointerX = this._pointerX;
  22553. this._unTranslatedPointerY = this._pointerY;
  22554. };
  22555. Scene.prototype._createUbo = function () {
  22556. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22557. this._sceneUbo.addUniform("viewProjection", 16);
  22558. this._sceneUbo.addUniform("view", 16);
  22559. };
  22560. Scene.prototype._createAlternateUbo = function () {
  22561. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22562. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22563. this._alternateSceneUbo.addUniform("view", 16);
  22564. };
  22565. // Pointers handling
  22566. /**
  22567. * Use this method to simulate a pointer move on a mesh
  22568. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22569. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22570. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22571. */
  22572. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22573. var evt = new PointerEvent("pointermove", pointerEventInit);
  22574. return this._processPointerMove(pickResult, evt);
  22575. };
  22576. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22577. var canvas = this._engine.getRenderingCanvas();
  22578. if (!canvas) {
  22579. return this;
  22580. }
  22581. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22582. this.setPointerOverSprite(null);
  22583. this.setPointerOverMesh(pickResult.pickedMesh);
  22584. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22585. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22586. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22587. }
  22588. else {
  22589. canvas.style.cursor = this.hoverCursor;
  22590. }
  22591. }
  22592. else {
  22593. canvas.style.cursor = this.defaultCursor;
  22594. }
  22595. }
  22596. else {
  22597. this.setPointerOverMesh(null);
  22598. // Sprites
  22599. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22600. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22601. this.setPointerOverSprite(pickResult.pickedSprite);
  22602. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22603. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22604. }
  22605. else {
  22606. canvas.style.cursor = this.hoverCursor;
  22607. }
  22608. }
  22609. else {
  22610. this.setPointerOverSprite(null);
  22611. // Restore pointer
  22612. canvas.style.cursor = this.defaultCursor;
  22613. }
  22614. }
  22615. if (pickResult) {
  22616. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22617. if (this.onPointerMove) {
  22618. this.onPointerMove(evt, pickResult, type);
  22619. }
  22620. if (this.onPointerObservable.hasObservers()) {
  22621. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22622. this.onPointerObservable.notifyObservers(pi, type);
  22623. }
  22624. }
  22625. return this;
  22626. };
  22627. /**
  22628. * Use this method to simulate a pointer down on a mesh
  22629. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22630. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22631. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22632. */
  22633. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22634. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22635. return this._processPointerDown(pickResult, evt);
  22636. };
  22637. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22638. var _this = this;
  22639. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22640. this._pickedDownMesh = pickResult.pickedMesh;
  22641. var actionManager = pickResult.pickedMesh.actionManager;
  22642. if (actionManager) {
  22643. if (actionManager.hasPickTriggers) {
  22644. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22645. switch (evt.button) {
  22646. case 0:
  22647. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22648. break;
  22649. case 1:
  22650. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22651. break;
  22652. case 2:
  22653. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22654. break;
  22655. }
  22656. }
  22657. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22658. window.setTimeout(function () {
  22659. 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);
  22660. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22661. if (_this._totalPointersPressed !== 0 &&
  22662. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22663. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22664. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22665. _this._startingPointerTime = 0;
  22666. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22667. }
  22668. }
  22669. }, Scene.LongPressDelay);
  22670. }
  22671. }
  22672. }
  22673. if (pickResult) {
  22674. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22675. if (this.onPointerDown) {
  22676. this.onPointerDown(evt, pickResult, type);
  22677. }
  22678. if (this.onPointerObservable.hasObservers()) {
  22679. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22680. this.onPointerObservable.notifyObservers(pi, type);
  22681. }
  22682. }
  22683. return this;
  22684. };
  22685. /**
  22686. * Use this method to simulate a pointer up on a mesh
  22687. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22688. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22689. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22690. */
  22691. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22692. var evt = new PointerEvent("pointerup", pointerEventInit);
  22693. var clickInfo = new ClickInfo();
  22694. clickInfo.singleClick = true;
  22695. clickInfo.ignore = true;
  22696. return this._processPointerUp(pickResult, evt, clickInfo);
  22697. };
  22698. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22699. if (pickResult && pickResult && pickResult.pickedMesh) {
  22700. this._pickedUpMesh = pickResult.pickedMesh;
  22701. if (this._pickedDownMesh === this._pickedUpMesh) {
  22702. if (this.onPointerPick) {
  22703. this.onPointerPick(evt, pickResult);
  22704. }
  22705. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22706. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22707. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22708. this.onPointerObservable.notifyObservers(pi, type_1);
  22709. }
  22710. }
  22711. if (pickResult.pickedMesh.actionManager) {
  22712. if (clickInfo.ignore) {
  22713. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22714. }
  22715. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22716. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22717. }
  22718. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22719. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22720. }
  22721. }
  22722. }
  22723. if (this._pickedDownMesh &&
  22724. this._pickedDownMesh.actionManager &&
  22725. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22726. this._pickedDownMesh !== this._pickedUpMesh) {
  22727. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22728. }
  22729. var type = BABYLON.PointerEventTypes.POINTERUP;
  22730. if (this.onPointerObservable.hasObservers()) {
  22731. if (!clickInfo.ignore) {
  22732. if (!clickInfo.hasSwiped) {
  22733. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22734. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  22735. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  22736. this.onPointerObservable.notifyObservers(pi, type_2);
  22737. }
  22738. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22739. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22740. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  22741. this.onPointerObservable.notifyObservers(pi, type_3);
  22742. }
  22743. }
  22744. }
  22745. else {
  22746. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22747. this.onPointerObservable.notifyObservers(pi, type);
  22748. }
  22749. }
  22750. if (this.onPointerUp) {
  22751. this.onPointerUp(evt, pickResult, type);
  22752. }
  22753. return this;
  22754. };
  22755. /**
  22756. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22757. * @param attachUp defines if you want to attach events to pointerup
  22758. * @param attachDown defines if you want to attach events to pointerdown
  22759. * @param attachMove defines if you want to attach events to pointermove
  22760. */
  22761. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22762. var _this = this;
  22763. if (attachUp === void 0) { attachUp = true; }
  22764. if (attachDown === void 0) { attachDown = true; }
  22765. if (attachMove === void 0) { attachMove = true; }
  22766. this._initActionManager = function (act, clickInfo) {
  22767. if (!_this._meshPickProceed) {
  22768. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22769. _this._currentPickResult = pickResult;
  22770. if (pickResult) {
  22771. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22772. }
  22773. _this._meshPickProceed = true;
  22774. }
  22775. return act;
  22776. };
  22777. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22778. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22779. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22780. btn !== _this._previousButtonPressed) {
  22781. _this._doubleClickOccured = false;
  22782. clickInfo.singleClick = true;
  22783. clickInfo.ignore = false;
  22784. cb(clickInfo, _this._currentPickResult);
  22785. }
  22786. };
  22787. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22788. var clickInfo = new ClickInfo();
  22789. _this._currentPickResult = null;
  22790. var act = null;
  22791. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22792. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22793. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22794. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22795. act = _this._initActionManager(act, clickInfo);
  22796. if (act)
  22797. checkPicking = act.hasPickTriggers;
  22798. }
  22799. if (checkPicking) {
  22800. var btn = evt.button;
  22801. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22802. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22803. if (!clickInfo.hasSwiped) {
  22804. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22805. if (!checkSingleClickImmediately) {
  22806. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22807. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22808. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22809. act = _this._initActionManager(act, clickInfo);
  22810. if (act)
  22811. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22812. }
  22813. }
  22814. if (checkSingleClickImmediately) {
  22815. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22816. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22817. btn !== _this._previousButtonPressed) {
  22818. clickInfo.singleClick = true;
  22819. cb(clickInfo, _this._currentPickResult);
  22820. }
  22821. }
  22822. else {
  22823. // wait that no double click has been raised during the double click delay
  22824. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22825. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22826. }
  22827. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22828. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22829. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22830. act = _this._initActionManager(act, clickInfo);
  22831. if (act)
  22832. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22833. }
  22834. if (checkDoubleClick) {
  22835. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22836. if (btn === _this._previousButtonPressed &&
  22837. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22838. !_this._doubleClickOccured) {
  22839. // pointer has not moved for 2 clicks, it's a double click
  22840. if (!clickInfo.hasSwiped &&
  22841. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22842. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22843. _this._previousStartingPointerTime = 0;
  22844. _this._doubleClickOccured = true;
  22845. clickInfo.doubleClick = true;
  22846. clickInfo.ignore = false;
  22847. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22848. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22849. }
  22850. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22851. cb(clickInfo, _this._currentPickResult);
  22852. }
  22853. else {
  22854. _this._doubleClickOccured = false;
  22855. _this._previousStartingPointerTime = _this._startingPointerTime;
  22856. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22857. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22858. _this._previousButtonPressed = btn;
  22859. if (Scene.ExclusiveDoubleClickMode) {
  22860. if (_this._previousDelayedSimpleClickTimeout) {
  22861. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22862. }
  22863. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22864. cb(clickInfo, _this._previousPickResult);
  22865. }
  22866. else {
  22867. cb(clickInfo, _this._currentPickResult);
  22868. }
  22869. }
  22870. }
  22871. else {
  22872. _this._doubleClickOccured = false;
  22873. _this._previousStartingPointerTime = _this._startingPointerTime;
  22874. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22875. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22876. _this._previousButtonPressed = btn;
  22877. }
  22878. }
  22879. }
  22880. }
  22881. clickInfo.ignore = true;
  22882. cb(clickInfo, _this._currentPickResult);
  22883. };
  22884. this._spritePredicate = function (sprite) {
  22885. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22886. };
  22887. this._onPointerMove = function (evt) {
  22888. _this._updatePointerPosition(evt);
  22889. // PreObservable support
  22890. if (_this.onPrePointerObservable.hasObservers()) {
  22891. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22892. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22893. _this.onPrePointerObservable.notifyObservers(pi, type);
  22894. if (pi.skipOnPointerObservable) {
  22895. return;
  22896. }
  22897. }
  22898. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22899. return;
  22900. }
  22901. if (!_this.pointerMovePredicate) {
  22902. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22903. }
  22904. // Meshes
  22905. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22906. _this._processPointerMove(pickResult, evt);
  22907. };
  22908. this._onPointerDown = function (evt) {
  22909. _this._totalPointersPressed++;
  22910. _this._pickedDownMesh = null;
  22911. _this._meshPickProceed = false;
  22912. _this._updatePointerPosition(evt);
  22913. if (_this.preventDefaultOnPointerDown && canvas) {
  22914. evt.preventDefault();
  22915. canvas.focus();
  22916. }
  22917. // PreObservable support
  22918. if (_this.onPrePointerObservable.hasObservers()) {
  22919. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22920. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22921. _this.onPrePointerObservable.notifyObservers(pi, type);
  22922. if (pi.skipOnPointerObservable) {
  22923. return;
  22924. }
  22925. }
  22926. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22927. return;
  22928. }
  22929. _this._startingPointerPosition.x = _this._pointerX;
  22930. _this._startingPointerPosition.y = _this._pointerY;
  22931. _this._startingPointerTime = new Date().getTime();
  22932. if (!_this.pointerDownPredicate) {
  22933. _this.pointerDownPredicate = function (mesh) {
  22934. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22935. };
  22936. }
  22937. // Meshes
  22938. _this._pickedDownMesh = null;
  22939. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22940. _this._processPointerDown(pickResult, evt);
  22941. // Sprites
  22942. _this._pickedDownSprite = null;
  22943. if (_this.spriteManagers.length > 0) {
  22944. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22945. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22946. if (pickResult.pickedSprite.actionManager) {
  22947. _this._pickedDownSprite = pickResult.pickedSprite;
  22948. switch (evt.button) {
  22949. case 0:
  22950. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22951. break;
  22952. case 1:
  22953. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22954. break;
  22955. case 2:
  22956. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22957. break;
  22958. }
  22959. if (pickResult.pickedSprite.actionManager) {
  22960. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22961. }
  22962. }
  22963. }
  22964. }
  22965. };
  22966. this._onPointerUp = function (evt) {
  22967. if (_this._totalPointersPressed === 0) {
  22968. return; // So we need to test it the pointer down was pressed before.
  22969. }
  22970. _this._totalPointersPressed--;
  22971. _this._pickedUpMesh = null;
  22972. _this._meshPickProceed = false;
  22973. _this._updatePointerPosition(evt);
  22974. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22975. // PreObservable support
  22976. if (_this.onPrePointerObservable.hasObservers()) {
  22977. if (!clickInfo.ignore) {
  22978. if (!clickInfo.hasSwiped) {
  22979. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22980. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22981. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22982. _this.onPrePointerObservable.notifyObservers(pi, type);
  22983. if (pi.skipOnPointerObservable) {
  22984. return;
  22985. }
  22986. }
  22987. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22988. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22989. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22990. _this.onPrePointerObservable.notifyObservers(pi, type);
  22991. if (pi.skipOnPointerObservable) {
  22992. return;
  22993. }
  22994. }
  22995. }
  22996. }
  22997. else {
  22998. var type = BABYLON.PointerEventTypes.POINTERUP;
  22999. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23000. _this.onPrePointerObservable.notifyObservers(pi, type);
  23001. if (pi.skipOnPointerObservable) {
  23002. return;
  23003. }
  23004. }
  23005. }
  23006. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  23007. return;
  23008. }
  23009. if (!_this.pointerUpPredicate) {
  23010. _this.pointerUpPredicate = function (mesh) {
  23011. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  23012. };
  23013. }
  23014. // Meshes
  23015. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  23016. _this._initActionManager(null, clickInfo);
  23017. }
  23018. if (!pickResult) {
  23019. pickResult = _this._currentPickResult;
  23020. }
  23021. _this._processPointerUp(pickResult, evt, clickInfo);
  23022. // Sprites
  23023. if (_this.spriteManagers.length > 0) {
  23024. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  23025. if (spritePickResult) {
  23026. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  23027. if (spritePickResult.pickedSprite.actionManager) {
  23028. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23029. if (spritePickResult.pickedSprite.actionManager) {
  23030. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  23031. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23032. }
  23033. }
  23034. }
  23035. }
  23036. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  23037. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  23038. }
  23039. }
  23040. }
  23041. _this._previousPickResult = _this._currentPickResult;
  23042. });
  23043. };
  23044. this._onKeyDown = function (evt) {
  23045. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  23046. if (_this.onPreKeyboardObservable.hasObservers()) {
  23047. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23048. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23049. if (pi.skipOnPointerObservable) {
  23050. return;
  23051. }
  23052. }
  23053. if (_this.onKeyboardObservable.hasObservers()) {
  23054. var pi = new BABYLON.KeyboardInfo(type, evt);
  23055. _this.onKeyboardObservable.notifyObservers(pi, type);
  23056. }
  23057. if (_this.actionManager) {
  23058. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23059. }
  23060. };
  23061. this._onKeyUp = function (evt) {
  23062. var type = BABYLON.KeyboardEventTypes.KEYUP;
  23063. if (_this.onPreKeyboardObservable.hasObservers()) {
  23064. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23065. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23066. if (pi.skipOnPointerObservable) {
  23067. return;
  23068. }
  23069. }
  23070. if (_this.onKeyboardObservable.hasObservers()) {
  23071. var pi = new BABYLON.KeyboardInfo(type, evt);
  23072. _this.onKeyboardObservable.notifyObservers(pi, type);
  23073. }
  23074. if (_this.actionManager) {
  23075. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23076. }
  23077. };
  23078. var engine = this.getEngine();
  23079. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  23080. if (!canvas) {
  23081. return;
  23082. }
  23083. canvas.addEventListener("keydown", _this._onKeyDown, false);
  23084. canvas.addEventListener("keyup", _this._onKeyUp, false);
  23085. });
  23086. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  23087. if (!canvas) {
  23088. return;
  23089. }
  23090. canvas.removeEventListener("keydown", _this._onKeyDown);
  23091. canvas.removeEventListener("keyup", _this._onKeyUp);
  23092. });
  23093. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23094. var canvas = this._engine.getRenderingCanvas();
  23095. if (!canvas) {
  23096. return;
  23097. }
  23098. if (attachMove) {
  23099. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  23100. // Wheel
  23101. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  23102. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  23103. }
  23104. if (attachDown) {
  23105. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  23106. }
  23107. if (attachUp) {
  23108. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  23109. }
  23110. canvas.tabIndex = 1;
  23111. };
  23112. Scene.prototype.detachControl = function () {
  23113. var engine = this.getEngine();
  23114. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23115. var canvas = engine.getRenderingCanvas();
  23116. if (!canvas) {
  23117. return;
  23118. }
  23119. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  23120. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  23121. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  23122. if (this._onCanvasBlurObserver) {
  23123. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  23124. }
  23125. if (this._onCanvasFocusObserver) {
  23126. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  23127. }
  23128. // Wheel
  23129. canvas.removeEventListener('mousewheel', this._onPointerMove);
  23130. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  23131. // Keyboard
  23132. canvas.removeEventListener("keydown", this._onKeyDown);
  23133. canvas.removeEventListener("keyup", this._onKeyUp);
  23134. // Observables
  23135. this.onKeyboardObservable.clear();
  23136. this.onPreKeyboardObservable.clear();
  23137. this.onPointerObservable.clear();
  23138. this.onPrePointerObservable.clear();
  23139. };
  23140. /**
  23141. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  23142. * Delay loaded resources are not taking in account
  23143. * @return true if all required resources are ready
  23144. */
  23145. Scene.prototype.isReady = function () {
  23146. if (this._isDisposed) {
  23147. return false;
  23148. }
  23149. if (this._pendingData.length > 0) {
  23150. return false;
  23151. }
  23152. var index;
  23153. var engine = this.getEngine();
  23154. // Geometries
  23155. for (index = 0; index < this._geometries.length; index++) {
  23156. var geometry = this._geometries[index];
  23157. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23158. return false;
  23159. }
  23160. }
  23161. // Meshes
  23162. for (index = 0; index < this.meshes.length; index++) {
  23163. var mesh = this.meshes[index];
  23164. if (!mesh.isEnabled()) {
  23165. continue;
  23166. }
  23167. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23168. continue;
  23169. }
  23170. if (!mesh.isReady(true)) {
  23171. return false;
  23172. }
  23173. // Effect layers
  23174. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  23175. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  23176. var layer = _a[_i];
  23177. if (!layer.hasMesh(mesh)) {
  23178. continue;
  23179. }
  23180. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23181. var subMesh = _c[_b];
  23182. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  23183. return false;
  23184. }
  23185. }
  23186. }
  23187. }
  23188. // Particles
  23189. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  23190. var particleSystem = _e[_d];
  23191. if (!particleSystem.isReady()) {
  23192. return false;
  23193. }
  23194. }
  23195. return true;
  23196. };
  23197. Scene.prototype.resetCachedMaterial = function () {
  23198. this._cachedMaterial = null;
  23199. this._cachedEffect = null;
  23200. this._cachedVisibility = null;
  23201. };
  23202. Scene.prototype.registerBeforeRender = function (func) {
  23203. this.onBeforeRenderObservable.add(func);
  23204. };
  23205. Scene.prototype.unregisterBeforeRender = function (func) {
  23206. this.onBeforeRenderObservable.removeCallback(func);
  23207. };
  23208. Scene.prototype.registerAfterRender = function (func) {
  23209. this.onAfterRenderObservable.add(func);
  23210. };
  23211. Scene.prototype.unregisterAfterRender = function (func) {
  23212. this.onAfterRenderObservable.removeCallback(func);
  23213. };
  23214. Scene.prototype._executeOnceBeforeRender = function (func) {
  23215. var _this = this;
  23216. var execFunc = function () {
  23217. func();
  23218. setTimeout(function () {
  23219. _this.unregisterBeforeRender(execFunc);
  23220. });
  23221. };
  23222. this.registerBeforeRender(execFunc);
  23223. };
  23224. /**
  23225. * The provided function will run before render once and will be disposed afterwards.
  23226. * A timeout delay can be provided so that the function will be executed in N ms.
  23227. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23228. * @param func The function to be executed.
  23229. * @param timeout optional delay in ms
  23230. */
  23231. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23232. var _this = this;
  23233. if (timeout !== undefined) {
  23234. setTimeout(function () {
  23235. _this._executeOnceBeforeRender(func);
  23236. }, timeout);
  23237. }
  23238. else {
  23239. this._executeOnceBeforeRender(func);
  23240. }
  23241. };
  23242. Scene.prototype._addPendingData = function (data) {
  23243. this._pendingData.push(data);
  23244. };
  23245. Scene.prototype._removePendingData = function (data) {
  23246. var wasLoading = this.isLoading;
  23247. var index = this._pendingData.indexOf(data);
  23248. if (index !== -1) {
  23249. this._pendingData.splice(index, 1);
  23250. }
  23251. if (wasLoading && !this.isLoading) {
  23252. this.onDataLoadedObservable.notifyObservers(this);
  23253. }
  23254. };
  23255. Scene.prototype.getWaitingItemsCount = function () {
  23256. return this._pendingData.length;
  23257. };
  23258. Object.defineProperty(Scene.prototype, "isLoading", {
  23259. get: function () {
  23260. return this._pendingData.length > 0;
  23261. },
  23262. enumerable: true,
  23263. configurable: true
  23264. });
  23265. /**
  23266. * Registers a function to be executed when the scene is ready.
  23267. * @param {Function} func - the function to be executed.
  23268. */
  23269. Scene.prototype.executeWhenReady = function (func) {
  23270. var _this = this;
  23271. this.onReadyObservable.add(func);
  23272. if (this._executeWhenReadyTimeoutId !== -1) {
  23273. return;
  23274. }
  23275. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23276. _this._checkIsReady();
  23277. }, 150);
  23278. };
  23279. /**
  23280. * Returns a promise that resolves when the scene is ready.
  23281. * @returns A promise that resolves when the scene is ready.
  23282. */
  23283. Scene.prototype.whenReadyAsync = function () {
  23284. var _this = this;
  23285. return new Promise(function (resolve) {
  23286. _this.executeWhenReady(function () {
  23287. resolve();
  23288. });
  23289. });
  23290. };
  23291. Scene.prototype._checkIsReady = function () {
  23292. var _this = this;
  23293. if (this.isReady()) {
  23294. this.onReadyObservable.notifyObservers(this);
  23295. this.onReadyObservable.clear();
  23296. this._executeWhenReadyTimeoutId = -1;
  23297. return;
  23298. }
  23299. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23300. _this._checkIsReady();
  23301. }, 150);
  23302. };
  23303. // Animations
  23304. /**
  23305. * Will start the animation sequence of a given target
  23306. * @param target defines the target
  23307. * @param from defines from which frame should animation start
  23308. * @param to defines until which frame should animation run.
  23309. * @param weight defines the weight to apply to the animation (1.0 by default)
  23310. * @param loop defines if the animation loops
  23311. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23312. * @param onAnimationEnd defines the function to be executed when the animation ends
  23313. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23314. * @returns the animatable object created for this animation
  23315. * @see BABYLON.Animatable
  23316. */
  23317. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  23318. if (weight === void 0) { weight = 1.0; }
  23319. if (speedRatio === void 0) { speedRatio = 1.0; }
  23320. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  23321. returnedAnimatable.weight = weight;
  23322. return returnedAnimatable;
  23323. };
  23324. /**
  23325. * Will start the animation sequence of a given target
  23326. * @param target defines the target
  23327. * @param from defines from which frame should animation start
  23328. * @param to defines until which frame should animation run.
  23329. * @param loop defines if the animation loops
  23330. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23331. * @param onAnimationEnd defines the function to be executed when the animation ends
  23332. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23333. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  23334. * @returns the animatable object created for this animation
  23335. * @see BABYLON.Animatable
  23336. */
  23337. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  23338. if (speedRatio === void 0) { speedRatio = 1.0; }
  23339. if (stopCurrent === void 0) { stopCurrent = true; }
  23340. if (from > to && speedRatio > 0) {
  23341. speedRatio *= -1;
  23342. }
  23343. if (stopCurrent) {
  23344. this.stopAnimation(target);
  23345. }
  23346. if (!animatable) {
  23347. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23348. }
  23349. // Local animations
  23350. if (target.animations) {
  23351. animatable.appendAnimations(target, target.animations);
  23352. }
  23353. // Children animations
  23354. if (target.getAnimatables) {
  23355. var animatables = target.getAnimatables();
  23356. for (var index = 0; index < animatables.length; index++) {
  23357. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  23358. }
  23359. }
  23360. animatable.reset();
  23361. return animatable;
  23362. };
  23363. /**
  23364. * Begin a new animation on a given node
  23365. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23366. * @param {BABYLON.Animation[]} defines the list of animations to start
  23367. * @param {number} from defines the initial value
  23368. * @param {number} to defines the final value
  23369. * @param {boolean} loop defines if you want animation to loop (off by default)
  23370. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23371. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23372. * @returns the list of created animatables
  23373. */
  23374. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23375. if (speedRatio === undefined) {
  23376. speedRatio = 1.0;
  23377. }
  23378. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23379. return animatable;
  23380. };
  23381. /**
  23382. * Begin a new animation on a given node and its hierarchy
  23383. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23384. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  23385. * @param {BABYLON.Animation[]} defines the list of animations to start
  23386. * @param {number} from defines the initial value
  23387. * @param {number} to defines the final value
  23388. * @param {boolean} loop defines if you want animation to loop (off by default)
  23389. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23390. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23391. * @returns the list of animatables created for all nodes
  23392. */
  23393. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23394. var children = target.getDescendants(directDescendantsOnly);
  23395. var result = [];
  23396. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23397. var child = children_1[_i];
  23398. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23399. }
  23400. return result;
  23401. };
  23402. Scene.prototype.getAnimatableByTarget = function (target) {
  23403. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23404. if (this._activeAnimatables[index].target === target) {
  23405. return this._activeAnimatables[index];
  23406. }
  23407. }
  23408. return null;
  23409. };
  23410. /**
  23411. * Gets all animatables associated with a given target
  23412. * @param target defines the target to look animatables for
  23413. * @returns an array of Animatables
  23414. */
  23415. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  23416. var result = [];
  23417. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23418. if (this._activeAnimatables[index].target === target) {
  23419. result.push(this._activeAnimatables[index]);
  23420. }
  23421. }
  23422. return result;
  23423. };
  23424. Object.defineProperty(Scene.prototype, "animatables", {
  23425. get: function () {
  23426. return this._activeAnimatables;
  23427. },
  23428. enumerable: true,
  23429. configurable: true
  23430. });
  23431. /**
  23432. * Will stop the animation of the given target
  23433. * @param target - the target
  23434. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  23435. * @see beginAnimation
  23436. */
  23437. Scene.prototype.stopAnimation = function (target, animationName) {
  23438. var animatables = this.getAllAnimatablesByTarget(target);
  23439. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  23440. var animatable = animatables_1[_i];
  23441. animatable.stop(animationName);
  23442. }
  23443. };
  23444. /**
  23445. * Stops and removes all animations that have been applied to the scene
  23446. */
  23447. Scene.prototype.stopAllAnimations = function () {
  23448. if (this._activeAnimatables) {
  23449. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23450. this._activeAnimatables[i].stop();
  23451. }
  23452. this._activeAnimatables = [];
  23453. }
  23454. };
  23455. Scene.prototype._animate = function () {
  23456. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23457. return;
  23458. }
  23459. // Getting time
  23460. var now = BABYLON.Tools.Now;
  23461. if (!this._animationTimeLast) {
  23462. if (this._pendingData.length > 0) {
  23463. return;
  23464. }
  23465. this._animationTimeLast = now;
  23466. }
  23467. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23468. this._animationTime += deltaTime;
  23469. this._animationTimeLast = now;
  23470. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23471. this._activeAnimatables[index]._animate(this._animationTime);
  23472. }
  23473. // Late animation bindings
  23474. this._processLateAnimationBindings();
  23475. };
  23476. /** @ignore */
  23477. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  23478. var target = runtimeAnimation.target;
  23479. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  23480. if (!target._lateAnimationHolders) {
  23481. target._lateAnimationHolders = {};
  23482. }
  23483. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  23484. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  23485. totalWeight: 0,
  23486. animations: []
  23487. };
  23488. }
  23489. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  23490. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  23491. };
  23492. Scene.prototype._processLateAnimationBindings = function () {
  23493. if (!this._registeredForLateAnimationBindings.length) {
  23494. return;
  23495. }
  23496. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  23497. var target = this._registeredForLateAnimationBindings.data[index];
  23498. for (var path in target._lateAnimationHolders) {
  23499. var holder = target._lateAnimationHolders[path];
  23500. // Sanity check
  23501. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  23502. continue;
  23503. }
  23504. var normalizer = 1.0;
  23505. var finalValue = void 0;
  23506. if (holder.totalWeight < 1.0) {
  23507. // We need to mix the original value in
  23508. var originalValue = holder.animations[0].originalValue;
  23509. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  23510. }
  23511. else {
  23512. // We need to normalize the weights
  23513. normalizer = holder.totalWeight;
  23514. }
  23515. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  23516. var runtimeAnimation = holder.animations[animIndex];
  23517. if (finalValue) {
  23518. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  23519. }
  23520. else {
  23521. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  23522. }
  23523. }
  23524. runtimeAnimation.target[path] = finalValue;
  23525. }
  23526. target._lateAnimationHolders = {};
  23527. }
  23528. this._registeredForLateAnimationBindings.reset();
  23529. };
  23530. // Matrix
  23531. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23532. this._useAlternateCameraConfiguration = active;
  23533. };
  23534. Scene.prototype.getViewMatrix = function () {
  23535. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23536. };
  23537. Scene.prototype.getProjectionMatrix = function () {
  23538. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23539. };
  23540. Scene.prototype.getTransformMatrix = function () {
  23541. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23542. };
  23543. Scene.prototype.setTransformMatrix = function (view, projection) {
  23544. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23545. return;
  23546. }
  23547. this._viewUpdateFlag = view.updateFlag;
  23548. this._projectionUpdateFlag = projection.updateFlag;
  23549. this._viewMatrix = view;
  23550. this._projectionMatrix = projection;
  23551. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23552. // Update frustum
  23553. if (!this._frustumPlanes) {
  23554. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23555. }
  23556. else {
  23557. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23558. }
  23559. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23560. var otherCamera = this.activeCamera._alternateCamera;
  23561. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23562. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23563. }
  23564. if (this._sceneUbo.useUbo) {
  23565. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23566. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23567. this._sceneUbo.update();
  23568. }
  23569. };
  23570. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23571. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23572. return;
  23573. }
  23574. this._alternateViewUpdateFlag = view.updateFlag;
  23575. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23576. this._alternateViewMatrix = view;
  23577. this._alternateProjectionMatrix = projection;
  23578. if (!this._alternateTransformMatrix) {
  23579. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23580. }
  23581. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23582. if (!this._alternateSceneUbo) {
  23583. this._createAlternateUbo();
  23584. }
  23585. if (this._alternateSceneUbo.useUbo) {
  23586. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23587. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23588. this._alternateSceneUbo.update();
  23589. }
  23590. };
  23591. Scene.prototype.getSceneUniformBuffer = function () {
  23592. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23593. };
  23594. // Methods
  23595. Scene.prototype.getUniqueId = function () {
  23596. var result = Scene._uniqueIdCounter;
  23597. Scene._uniqueIdCounter++;
  23598. return result;
  23599. };
  23600. Scene.prototype.addMesh = function (newMesh) {
  23601. this.meshes.push(newMesh);
  23602. //notify the collision coordinator
  23603. if (this.collisionCoordinator) {
  23604. this.collisionCoordinator.onMeshAdded(newMesh);
  23605. }
  23606. newMesh._resyncLightSources();
  23607. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23608. };
  23609. Scene.prototype.removeMesh = function (toRemove) {
  23610. var index = this.meshes.indexOf(toRemove);
  23611. if (index !== -1) {
  23612. // Remove from the scene if mesh found
  23613. this.meshes.splice(index, 1);
  23614. }
  23615. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23616. return index;
  23617. };
  23618. Scene.prototype.addTransformNode = function (newTransformNode) {
  23619. this.transformNodes.push(newTransformNode);
  23620. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23621. };
  23622. Scene.prototype.removeTransformNode = function (toRemove) {
  23623. var index = this.transformNodes.indexOf(toRemove);
  23624. if (index !== -1) {
  23625. // Remove from the scene if found
  23626. this.transformNodes.splice(index, 1);
  23627. }
  23628. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23629. return index;
  23630. };
  23631. Scene.prototype.removeSkeleton = function (toRemove) {
  23632. var index = this.skeletons.indexOf(toRemove);
  23633. if (index !== -1) {
  23634. // Remove from the scene if found
  23635. this.skeletons.splice(index, 1);
  23636. }
  23637. return index;
  23638. };
  23639. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23640. var index = this.morphTargetManagers.indexOf(toRemove);
  23641. if (index !== -1) {
  23642. // Remove from the scene if found
  23643. this.morphTargetManagers.splice(index, 1);
  23644. }
  23645. return index;
  23646. };
  23647. Scene.prototype.removeLight = function (toRemove) {
  23648. var index = this.lights.indexOf(toRemove);
  23649. if (index !== -1) {
  23650. // Remove from meshes
  23651. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23652. var mesh = _a[_i];
  23653. mesh._removeLightSource(toRemove);
  23654. }
  23655. // Remove from the scene if mesh found
  23656. this.lights.splice(index, 1);
  23657. this.sortLightsByPriority();
  23658. }
  23659. this.onLightRemovedObservable.notifyObservers(toRemove);
  23660. return index;
  23661. };
  23662. Scene.prototype.removeCamera = function (toRemove) {
  23663. var index = this.cameras.indexOf(toRemove);
  23664. if (index !== -1) {
  23665. // Remove from the scene if mesh found
  23666. this.cameras.splice(index, 1);
  23667. }
  23668. // Remove from activeCameras
  23669. var index2 = this.activeCameras.indexOf(toRemove);
  23670. if (index2 !== -1) {
  23671. // Remove from the scene if mesh found
  23672. this.activeCameras.splice(index2, 1);
  23673. }
  23674. // Reset the activeCamera
  23675. if (this.activeCamera === toRemove) {
  23676. if (this.cameras.length > 0) {
  23677. this.activeCamera = this.cameras[0];
  23678. }
  23679. else {
  23680. this.activeCamera = null;
  23681. }
  23682. }
  23683. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23684. return index;
  23685. };
  23686. Scene.prototype.removeParticleSystem = function (toRemove) {
  23687. var index = this.particleSystems.indexOf(toRemove);
  23688. if (index !== -1) {
  23689. this.particleSystems.splice(index, 1);
  23690. }
  23691. return index;
  23692. };
  23693. ;
  23694. Scene.prototype.removeAnimation = function (toRemove) {
  23695. var index = this.animations.indexOf(toRemove);
  23696. if (index !== -1) {
  23697. this.animations.splice(index, 1);
  23698. }
  23699. return index;
  23700. };
  23701. ;
  23702. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23703. var index = this.multiMaterials.indexOf(toRemove);
  23704. if (index !== -1) {
  23705. this.multiMaterials.splice(index, 1);
  23706. }
  23707. return index;
  23708. };
  23709. ;
  23710. Scene.prototype.removeMaterial = function (toRemove) {
  23711. var index = this.materials.indexOf(toRemove);
  23712. if (index !== -1) {
  23713. this.materials.splice(index, 1);
  23714. }
  23715. return index;
  23716. };
  23717. ;
  23718. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23719. var index = this.lensFlareSystems.indexOf(toRemove);
  23720. if (index !== -1) {
  23721. this.lensFlareSystems.splice(index, 1);
  23722. }
  23723. return index;
  23724. };
  23725. ;
  23726. Scene.prototype.removeActionManager = function (toRemove) {
  23727. var index = this._actionManagers.indexOf(toRemove);
  23728. if (index !== -1) {
  23729. this._actionManagers.splice(index, 1);
  23730. }
  23731. return index;
  23732. };
  23733. ;
  23734. Scene.prototype.addLight = function (newLight) {
  23735. this.lights.push(newLight);
  23736. this.sortLightsByPriority();
  23737. // Add light to all meshes (To support if the light is removed and then readded)
  23738. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23739. var mesh = _a[_i];
  23740. if (mesh._lightSources.indexOf(newLight) === -1) {
  23741. mesh._lightSources.push(newLight);
  23742. mesh._resyncLightSources();
  23743. }
  23744. }
  23745. this.onNewLightAddedObservable.notifyObservers(newLight);
  23746. };
  23747. Scene.prototype.sortLightsByPriority = function () {
  23748. if (this.requireLightSorting) {
  23749. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23750. }
  23751. };
  23752. Scene.prototype.addCamera = function (newCamera) {
  23753. this.cameras.push(newCamera);
  23754. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23755. };
  23756. Scene.prototype.addSkeleton = function (newSkeleton) {
  23757. this.skeletons.push(newSkeleton);
  23758. };
  23759. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23760. this.particleSystems.push(newParticleSystem);
  23761. };
  23762. Scene.prototype.addAnimation = function (newAnimation) {
  23763. this.animations.push(newAnimation);
  23764. };
  23765. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23766. this.multiMaterials.push(newMultiMaterial);
  23767. };
  23768. Scene.prototype.addMaterial = function (newMaterial) {
  23769. this.materials.push(newMaterial);
  23770. };
  23771. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23772. this.morphTargetManagers.push(newMorphTargetManager);
  23773. };
  23774. Scene.prototype.addGeometry = function (newGeometrie) {
  23775. this._geometries.push(newGeometrie);
  23776. };
  23777. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23778. this.lensFlareSystems.push(newLensFlareSystem);
  23779. };
  23780. Scene.prototype.addActionManager = function (newActionManager) {
  23781. this._actionManagers.push(newActionManager);
  23782. };
  23783. /**
  23784. * Switch active camera
  23785. * @param {Camera} newCamera - new active camera
  23786. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23787. */
  23788. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23789. if (attachControl === void 0) { attachControl = true; }
  23790. var canvas = this._engine.getRenderingCanvas();
  23791. if (!canvas) {
  23792. return;
  23793. }
  23794. if (this.activeCamera) {
  23795. this.activeCamera.detachControl(canvas);
  23796. }
  23797. this.activeCamera = newCamera;
  23798. if (attachControl) {
  23799. newCamera.attachControl(canvas);
  23800. }
  23801. };
  23802. /**
  23803. * sets the active camera of the scene using its ID
  23804. * @param {string} id - the camera's ID
  23805. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23806. * @see activeCamera
  23807. */
  23808. Scene.prototype.setActiveCameraByID = function (id) {
  23809. var camera = this.getCameraByID(id);
  23810. if (camera) {
  23811. this.activeCamera = camera;
  23812. return camera;
  23813. }
  23814. return null;
  23815. };
  23816. /**
  23817. * sets the active camera of the scene using its name
  23818. * @param {string} name - the camera's name
  23819. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23820. * @see activeCamera
  23821. */
  23822. Scene.prototype.setActiveCameraByName = function (name) {
  23823. var camera = this.getCameraByName(name);
  23824. if (camera) {
  23825. this.activeCamera = camera;
  23826. return camera;
  23827. }
  23828. return null;
  23829. };
  23830. /**
  23831. * get an animation group using its name
  23832. * @param {string} the material's name
  23833. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23834. */
  23835. Scene.prototype.getAnimationGroupByName = function (name) {
  23836. for (var index = 0; index < this.animationGroups.length; index++) {
  23837. if (this.animationGroups[index].name === name) {
  23838. return this.animationGroups[index];
  23839. }
  23840. }
  23841. return null;
  23842. };
  23843. /**
  23844. * get a material using its id
  23845. * @param {string} the material's ID
  23846. * @return {BABYLON.Material|null} the material or null if none found.
  23847. */
  23848. Scene.prototype.getMaterialByID = function (id) {
  23849. for (var index = 0; index < this.materials.length; index++) {
  23850. if (this.materials[index].id === id) {
  23851. return this.materials[index];
  23852. }
  23853. }
  23854. return null;
  23855. };
  23856. /**
  23857. * get a material using its name
  23858. * @param {string} the material's name
  23859. * @return {BABYLON.Material|null} the material or null if none found.
  23860. */
  23861. Scene.prototype.getMaterialByName = function (name) {
  23862. for (var index = 0; index < this.materials.length; index++) {
  23863. if (this.materials[index].name === name) {
  23864. return this.materials[index];
  23865. }
  23866. }
  23867. return null;
  23868. };
  23869. Scene.prototype.getLensFlareSystemByName = function (name) {
  23870. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23871. if (this.lensFlareSystems[index].name === name) {
  23872. return this.lensFlareSystems[index];
  23873. }
  23874. }
  23875. return null;
  23876. };
  23877. Scene.prototype.getLensFlareSystemByID = function (id) {
  23878. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23879. if (this.lensFlareSystems[index].id === id) {
  23880. return this.lensFlareSystems[index];
  23881. }
  23882. }
  23883. return null;
  23884. };
  23885. Scene.prototype.getCameraByID = function (id) {
  23886. for (var index = 0; index < this.cameras.length; index++) {
  23887. if (this.cameras[index].id === id) {
  23888. return this.cameras[index];
  23889. }
  23890. }
  23891. return null;
  23892. };
  23893. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23894. for (var index = 0; index < this.cameras.length; index++) {
  23895. if (this.cameras[index].uniqueId === uniqueId) {
  23896. return this.cameras[index];
  23897. }
  23898. }
  23899. return null;
  23900. };
  23901. /**
  23902. * get a camera using its name
  23903. * @param {string} the camera's name
  23904. * @return {BABYLON.Camera|null} the camera or null if none found.
  23905. */
  23906. Scene.prototype.getCameraByName = function (name) {
  23907. for (var index = 0; index < this.cameras.length; index++) {
  23908. if (this.cameras[index].name === name) {
  23909. return this.cameras[index];
  23910. }
  23911. }
  23912. return null;
  23913. };
  23914. /**
  23915. * get a bone using its id
  23916. * @param {string} the bone's id
  23917. * @return {BABYLON.Bone|null} the bone or null if not found
  23918. */
  23919. Scene.prototype.getBoneByID = function (id) {
  23920. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23921. var skeleton = this.skeletons[skeletonIndex];
  23922. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23923. if (skeleton.bones[boneIndex].id === id) {
  23924. return skeleton.bones[boneIndex];
  23925. }
  23926. }
  23927. }
  23928. return null;
  23929. };
  23930. /**
  23931. * get a bone using its id
  23932. * @param {string} the bone's name
  23933. * @return {BABYLON.Bone|null} the bone or null if not found
  23934. */
  23935. Scene.prototype.getBoneByName = function (name) {
  23936. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23937. var skeleton = this.skeletons[skeletonIndex];
  23938. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23939. if (skeleton.bones[boneIndex].name === name) {
  23940. return skeleton.bones[boneIndex];
  23941. }
  23942. }
  23943. }
  23944. return null;
  23945. };
  23946. /**
  23947. * get a light node using its name
  23948. * @param {string} the light's name
  23949. * @return {BABYLON.Light|null} the light or null if none found.
  23950. */
  23951. Scene.prototype.getLightByName = function (name) {
  23952. for (var index = 0; index < this.lights.length; index++) {
  23953. if (this.lights[index].name === name) {
  23954. return this.lights[index];
  23955. }
  23956. }
  23957. return null;
  23958. };
  23959. /**
  23960. * get a light node using its ID
  23961. * @param {string} the light's id
  23962. * @return {BABYLON.Light|null} the light or null if none found.
  23963. */
  23964. Scene.prototype.getLightByID = function (id) {
  23965. for (var index = 0; index < this.lights.length; index++) {
  23966. if (this.lights[index].id === id) {
  23967. return this.lights[index];
  23968. }
  23969. }
  23970. return null;
  23971. };
  23972. /**
  23973. * get a light node using its scene-generated unique ID
  23974. * @param {number} the light's unique id
  23975. * @return {BABYLON.Light|null} the light or null if none found.
  23976. */
  23977. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23978. for (var index = 0; index < this.lights.length; index++) {
  23979. if (this.lights[index].uniqueId === uniqueId) {
  23980. return this.lights[index];
  23981. }
  23982. }
  23983. return null;
  23984. };
  23985. /**
  23986. * get a particle system by id
  23987. * @param id {number} the particle system id
  23988. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23989. */
  23990. Scene.prototype.getParticleSystemByID = function (id) {
  23991. for (var index = 0; index < this.particleSystems.length; index++) {
  23992. if (this.particleSystems[index].id === id) {
  23993. return this.particleSystems[index];
  23994. }
  23995. }
  23996. return null;
  23997. };
  23998. /**
  23999. * get a geometry using its ID
  24000. * @param {string} the geometry's id
  24001. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  24002. */
  24003. Scene.prototype.getGeometryByID = function (id) {
  24004. for (var index = 0; index < this._geometries.length; index++) {
  24005. if (this._geometries[index].id === id) {
  24006. return this._geometries[index];
  24007. }
  24008. }
  24009. return null;
  24010. };
  24011. /**
  24012. * add a new geometry to this scene.
  24013. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  24014. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  24015. * @return {boolean} was the geometry added or not
  24016. */
  24017. Scene.prototype.pushGeometry = function (geometry, force) {
  24018. if (!force && this.getGeometryByID(geometry.id)) {
  24019. return false;
  24020. }
  24021. this._geometries.push(geometry);
  24022. //notify the collision coordinator
  24023. if (this.collisionCoordinator) {
  24024. this.collisionCoordinator.onGeometryAdded(geometry);
  24025. }
  24026. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  24027. return true;
  24028. };
  24029. /**
  24030. * Removes an existing geometry
  24031. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  24032. * @return {boolean} was the geometry removed or not
  24033. */
  24034. Scene.prototype.removeGeometry = function (geometry) {
  24035. var index = this._geometries.indexOf(geometry);
  24036. if (index > -1) {
  24037. this._geometries.splice(index, 1);
  24038. //notify the collision coordinator
  24039. if (this.collisionCoordinator) {
  24040. this.collisionCoordinator.onGeometryDeleted(geometry);
  24041. }
  24042. this.onGeometryRemovedObservable.notifyObservers(geometry);
  24043. return true;
  24044. }
  24045. return false;
  24046. };
  24047. Scene.prototype.getGeometries = function () {
  24048. return this._geometries;
  24049. };
  24050. /**
  24051. * Get the first added mesh found of a given ID
  24052. * @param {string} id - the id to search for
  24053. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24054. */
  24055. Scene.prototype.getMeshByID = function (id) {
  24056. for (var index = 0; index < this.meshes.length; index++) {
  24057. if (this.meshes[index].id === id) {
  24058. return this.meshes[index];
  24059. }
  24060. }
  24061. return null;
  24062. };
  24063. Scene.prototype.getMeshesByID = function (id) {
  24064. return this.meshes.filter(function (m) {
  24065. return m.id === id;
  24066. });
  24067. };
  24068. /**
  24069. * Get the first added transform node found of a given ID
  24070. * @param {string} id - the id to search for
  24071. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  24072. */
  24073. Scene.prototype.getTransformNodeByID = function (id) {
  24074. for (var index = 0; index < this.transformNodes.length; index++) {
  24075. if (this.transformNodes[index].id === id) {
  24076. return this.transformNodes[index];
  24077. }
  24078. }
  24079. return null;
  24080. };
  24081. Scene.prototype.getTransformNodesByID = function (id) {
  24082. return this.transformNodes.filter(function (m) {
  24083. return m.id === id;
  24084. });
  24085. };
  24086. /**
  24087. * Get a mesh with its auto-generated unique id
  24088. * @param {number} uniqueId - the unique id to search for
  24089. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24090. */
  24091. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  24092. for (var index = 0; index < this.meshes.length; index++) {
  24093. if (this.meshes[index].uniqueId === uniqueId) {
  24094. return this.meshes[index];
  24095. }
  24096. }
  24097. return null;
  24098. };
  24099. /**
  24100. * Get a the last added mesh found of a given ID
  24101. * @param {string} id - the id to search for
  24102. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24103. */
  24104. Scene.prototype.getLastMeshByID = function (id) {
  24105. for (var index = this.meshes.length - 1; index >= 0; index--) {
  24106. if (this.meshes[index].id === id) {
  24107. return this.meshes[index];
  24108. }
  24109. }
  24110. return null;
  24111. };
  24112. /**
  24113. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  24114. * @param {string} id - the id to search for
  24115. * @return {BABYLON.Node|null} the node found or null if not found at all.
  24116. */
  24117. Scene.prototype.getLastEntryByID = function (id) {
  24118. var index;
  24119. for (index = this.meshes.length - 1; index >= 0; index--) {
  24120. if (this.meshes[index].id === id) {
  24121. return this.meshes[index];
  24122. }
  24123. }
  24124. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  24125. if (this.transformNodes[index].id === id) {
  24126. return this.transformNodes[index];
  24127. }
  24128. }
  24129. for (index = this.cameras.length - 1; index >= 0; index--) {
  24130. if (this.cameras[index].id === id) {
  24131. return this.cameras[index];
  24132. }
  24133. }
  24134. for (index = this.lights.length - 1; index >= 0; index--) {
  24135. if (this.lights[index].id === id) {
  24136. return this.lights[index];
  24137. }
  24138. }
  24139. return null;
  24140. };
  24141. Scene.prototype.getNodeByID = function (id) {
  24142. var mesh = this.getMeshByID(id);
  24143. if (mesh) {
  24144. return mesh;
  24145. }
  24146. var light = this.getLightByID(id);
  24147. if (light) {
  24148. return light;
  24149. }
  24150. var camera = this.getCameraByID(id);
  24151. if (camera) {
  24152. return camera;
  24153. }
  24154. var bone = this.getBoneByID(id);
  24155. return bone;
  24156. };
  24157. Scene.prototype.getNodeByName = function (name) {
  24158. var mesh = this.getMeshByName(name);
  24159. if (mesh) {
  24160. return mesh;
  24161. }
  24162. var light = this.getLightByName(name);
  24163. if (light) {
  24164. return light;
  24165. }
  24166. var camera = this.getCameraByName(name);
  24167. if (camera) {
  24168. return camera;
  24169. }
  24170. var bone = this.getBoneByName(name);
  24171. return bone;
  24172. };
  24173. Scene.prototype.getMeshByName = function (name) {
  24174. for (var index = 0; index < this.meshes.length; index++) {
  24175. if (this.meshes[index].name === name) {
  24176. return this.meshes[index];
  24177. }
  24178. }
  24179. return null;
  24180. };
  24181. Scene.prototype.getTransformNodeByName = function (name) {
  24182. for (var index = 0; index < this.transformNodes.length; index++) {
  24183. if (this.transformNodes[index].name === name) {
  24184. return this.transformNodes[index];
  24185. }
  24186. }
  24187. return null;
  24188. };
  24189. Scene.prototype.getSoundByName = function (name) {
  24190. var index;
  24191. if (BABYLON.AudioEngine) {
  24192. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  24193. if (this.mainSoundTrack.soundCollection[index].name === name) {
  24194. return this.mainSoundTrack.soundCollection[index];
  24195. }
  24196. }
  24197. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  24198. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  24199. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  24200. return this.soundTracks[sdIndex].soundCollection[index];
  24201. }
  24202. }
  24203. }
  24204. }
  24205. return null;
  24206. };
  24207. Scene.prototype.getLastSkeletonByID = function (id) {
  24208. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  24209. if (this.skeletons[index].id === id) {
  24210. return this.skeletons[index];
  24211. }
  24212. }
  24213. return null;
  24214. };
  24215. Scene.prototype.getSkeletonById = function (id) {
  24216. for (var index = 0; index < this.skeletons.length; index++) {
  24217. if (this.skeletons[index].id === id) {
  24218. return this.skeletons[index];
  24219. }
  24220. }
  24221. return null;
  24222. };
  24223. Scene.prototype.getSkeletonByName = function (name) {
  24224. for (var index = 0; index < this.skeletons.length; index++) {
  24225. if (this.skeletons[index].name === name) {
  24226. return this.skeletons[index];
  24227. }
  24228. }
  24229. return null;
  24230. };
  24231. Scene.prototype.getMorphTargetManagerById = function (id) {
  24232. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  24233. if (this.morphTargetManagers[index].uniqueId === id) {
  24234. return this.morphTargetManagers[index];
  24235. }
  24236. }
  24237. return null;
  24238. };
  24239. Scene.prototype.isActiveMesh = function (mesh) {
  24240. return (this._activeMeshes.indexOf(mesh) !== -1);
  24241. };
  24242. /**
  24243. * Return a the first highlight layer of the scene with a given name.
  24244. * @param name The name of the highlight layer to look for.
  24245. * @return The highlight layer if found otherwise null.
  24246. */
  24247. Scene.prototype.getHighlightLayerByName = function (name) {
  24248. for (var index = 0; index < this.effectLayers.length; index++) {
  24249. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  24250. return this.effectLayers[index];
  24251. }
  24252. }
  24253. return null;
  24254. };
  24255. /**
  24256. * Return a the first highlight layer of the scene with a given name.
  24257. * @param name The name of the highlight layer to look for.
  24258. * @return The highlight layer if found otherwise null.
  24259. */
  24260. Scene.prototype.getGlowLayerByName = function (name) {
  24261. for (var index = 0; index < this.effectLayers.length; index++) {
  24262. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  24263. return this.effectLayers[index];
  24264. }
  24265. }
  24266. return null;
  24267. };
  24268. Object.defineProperty(Scene.prototype, "uid", {
  24269. /**
  24270. * Return a unique id as a string which can serve as an identifier for the scene
  24271. */
  24272. get: function () {
  24273. if (!this._uid) {
  24274. this._uid = BABYLON.Tools.RandomId();
  24275. }
  24276. return this._uid;
  24277. },
  24278. enumerable: true,
  24279. configurable: true
  24280. });
  24281. /**
  24282. * Add an externaly attached data from its key.
  24283. * This method call will fail and return false, if such key already exists.
  24284. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  24285. * @param key the unique key that identifies the data
  24286. * @param data the data object to associate to the key for this Engine instance
  24287. * @return true if no such key were already present and the data was added successfully, false otherwise
  24288. */
  24289. Scene.prototype.addExternalData = function (key, data) {
  24290. if (!this._externalData) {
  24291. this._externalData = new BABYLON.StringDictionary();
  24292. }
  24293. return this._externalData.add(key, data);
  24294. };
  24295. /**
  24296. * Get an externaly attached data from its key
  24297. * @param key the unique key that identifies the data
  24298. * @return the associated data, if present (can be null), or undefined if not present
  24299. */
  24300. Scene.prototype.getExternalData = function (key) {
  24301. if (!this._externalData) {
  24302. return null;
  24303. }
  24304. return this._externalData.get(key);
  24305. };
  24306. /**
  24307. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24308. * @param key the unique key that identifies the data
  24309. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24310. * @return the associated data, can be null if the factory returned null.
  24311. */
  24312. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24313. if (!this._externalData) {
  24314. this._externalData = new BABYLON.StringDictionary();
  24315. }
  24316. return this._externalData.getOrAddWithFactory(key, factory);
  24317. };
  24318. /**
  24319. * Remove an externaly attached data from the Engine instance
  24320. * @param key the unique key that identifies the data
  24321. * @return true if the data was successfully removed, false if it doesn't exist
  24322. */
  24323. Scene.prototype.removeExternalData = function (key) {
  24324. return this._externalData.remove(key);
  24325. };
  24326. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24327. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24328. if (mesh.showSubMeshesBoundingBox) {
  24329. var boundingInfo = subMesh.getBoundingInfo();
  24330. if (boundingInfo !== null && boundingInfo !== undefined) {
  24331. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24332. }
  24333. }
  24334. var material = subMesh.getMaterial();
  24335. if (material !== null && material !== undefined) {
  24336. // Render targets
  24337. if (material.getRenderTargetTextures !== undefined) {
  24338. if (this._processedMaterials.indexOf(material) === -1) {
  24339. this._processedMaterials.push(material);
  24340. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24341. }
  24342. }
  24343. // Dispatch
  24344. this._activeIndices.addCount(subMesh.indexCount, false);
  24345. this._renderingManager.dispatch(subMesh, mesh, material);
  24346. }
  24347. }
  24348. };
  24349. /**
  24350. * Clear the processed materials smart array preventing retention point in material dispose.
  24351. */
  24352. Scene.prototype.freeProcessedMaterials = function () {
  24353. this._processedMaterials.dispose();
  24354. };
  24355. /**
  24356. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24357. */
  24358. Scene.prototype.freeActiveMeshes = function () {
  24359. this._activeMeshes.dispose();
  24360. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24361. this.activeCamera._activeMeshes.dispose();
  24362. }
  24363. if (this.activeCameras) {
  24364. for (var i = 0; i < this.activeCameras.length; i++) {
  24365. var activeCamera = this.activeCameras[i];
  24366. if (activeCamera && activeCamera._activeMeshes) {
  24367. activeCamera._activeMeshes.dispose();
  24368. }
  24369. }
  24370. }
  24371. };
  24372. /**
  24373. * Clear the info related to rendering groups preventing retention points during dispose.
  24374. */
  24375. Scene.prototype.freeRenderingGroups = function () {
  24376. if (this._renderingManager) {
  24377. this._renderingManager.freeRenderingGroups();
  24378. }
  24379. if (this.textures) {
  24380. for (var i = 0; i < this.textures.length; i++) {
  24381. var texture = this.textures[i];
  24382. if (texture && texture.renderList) {
  24383. texture.freeRenderingGroups();
  24384. }
  24385. }
  24386. }
  24387. };
  24388. Scene.prototype._isInIntermediateRendering = function () {
  24389. return this._intermediateRendering;
  24390. };
  24391. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24392. this._activeMeshCandidateProvider = provider;
  24393. };
  24394. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24395. return this._activeMeshCandidateProvider;
  24396. };
  24397. /**
  24398. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24399. */
  24400. Scene.prototype.freezeActiveMeshes = function () {
  24401. if (!this.activeCamera) {
  24402. return this;
  24403. }
  24404. if (!this._frustumPlanes) {
  24405. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24406. }
  24407. this._evaluateActiveMeshes();
  24408. this._activeMeshesFrozen = true;
  24409. return this;
  24410. };
  24411. /**
  24412. * Use this function to restart evaluating active meshes on every frame
  24413. */
  24414. Scene.prototype.unfreezeActiveMeshes = function () {
  24415. this._activeMeshesFrozen = false;
  24416. return this;
  24417. };
  24418. Scene.prototype._evaluateActiveMeshes = function () {
  24419. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24420. return;
  24421. }
  24422. if (!this.activeCamera) {
  24423. return;
  24424. }
  24425. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24426. this.activeCamera._activeMeshes.reset();
  24427. this._activeMeshes.reset();
  24428. this._renderingManager.reset();
  24429. this._processedMaterials.reset();
  24430. this._activeParticleSystems.reset();
  24431. this._activeSkeletons.reset();
  24432. this._softwareSkinnedMeshes.reset();
  24433. if (this._boundingBoxRenderer) {
  24434. this._boundingBoxRenderer.reset();
  24435. }
  24436. // Meshes
  24437. var meshes;
  24438. var len;
  24439. var checkIsEnabled = true;
  24440. // Determine mesh candidates
  24441. if (this._activeMeshCandidateProvider !== undefined) {
  24442. // Use _activeMeshCandidateProvider
  24443. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24444. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24445. if (meshes !== undefined) {
  24446. len = meshes.length;
  24447. }
  24448. else {
  24449. len = 0;
  24450. }
  24451. }
  24452. else if (this._selectionOctree !== undefined) {
  24453. // Octree
  24454. var selection = this._selectionOctree.select(this._frustumPlanes);
  24455. meshes = selection.data;
  24456. len = selection.length;
  24457. }
  24458. else {
  24459. // Full scene traversal
  24460. len = this.meshes.length;
  24461. meshes = this.meshes;
  24462. }
  24463. // Check each mesh
  24464. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24465. mesh = meshes[meshIndex];
  24466. if (mesh.isBlocked) {
  24467. continue;
  24468. }
  24469. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24470. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24471. continue;
  24472. }
  24473. mesh.computeWorldMatrix();
  24474. // Intersections
  24475. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24476. this._meshesForIntersections.pushNoDuplicate(mesh);
  24477. }
  24478. // Switch to current LOD
  24479. meshLOD = mesh.getLOD(this.activeCamera);
  24480. if (meshLOD === undefined || meshLOD === null) {
  24481. continue;
  24482. }
  24483. mesh._preActivate();
  24484. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24485. this._activeMeshes.push(mesh);
  24486. this.activeCamera._activeMeshes.push(mesh);
  24487. mesh._activate(this._renderId);
  24488. if (meshLOD !== mesh) {
  24489. meshLOD._activate(this._renderId);
  24490. }
  24491. this._activeMesh(mesh, meshLOD);
  24492. }
  24493. }
  24494. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24495. // Particle systems
  24496. if (this.particlesEnabled) {
  24497. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24498. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24499. var particleSystem = this.particleSystems[particleIndex];
  24500. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24501. continue;
  24502. }
  24503. var emitter = particleSystem.emitter;
  24504. if (!emitter.position || emitter.isEnabled()) {
  24505. this._activeParticleSystems.push(particleSystem);
  24506. particleSystem.animate();
  24507. this._renderingManager.dispatchParticles(particleSystem);
  24508. }
  24509. }
  24510. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24511. }
  24512. };
  24513. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24514. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24515. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24516. mesh.skeleton.prepare();
  24517. }
  24518. if (!mesh.computeBonesUsingShaders) {
  24519. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24520. }
  24521. }
  24522. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24523. var boundingInfo = sourceMesh.getBoundingInfo();
  24524. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24525. }
  24526. if (mesh !== undefined && mesh !== null
  24527. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24528. // Submeshes Octrees
  24529. var len;
  24530. var subMeshes;
  24531. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24532. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24533. len = intersections.length;
  24534. subMeshes = intersections.data;
  24535. }
  24536. else {
  24537. subMeshes = mesh.subMeshes;
  24538. len = subMeshes.length;
  24539. }
  24540. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24541. subMesh = subMeshes[subIndex];
  24542. this._evaluateSubMesh(subMesh, mesh);
  24543. }
  24544. }
  24545. };
  24546. Scene.prototype.updateTransformMatrix = function (force) {
  24547. if (!this.activeCamera) {
  24548. return;
  24549. }
  24550. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24551. };
  24552. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24553. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24554. };
  24555. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24556. if (camera && camera._skipRendering) {
  24557. return;
  24558. }
  24559. var engine = this._engine;
  24560. this.activeCamera = camera;
  24561. if (!this.activeCamera)
  24562. throw new Error("Active camera not set");
  24563. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24564. // Viewport
  24565. engine.setViewport(this.activeCamera.viewport);
  24566. // Camera
  24567. this.resetCachedMaterial();
  24568. this._renderId++;
  24569. this.updateTransformMatrix();
  24570. if (camera._alternateCamera) {
  24571. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24572. this._alternateRendering = true;
  24573. }
  24574. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24575. // Meshes
  24576. this._evaluateActiveMeshes();
  24577. // Software skinning
  24578. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24579. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24580. mesh.applySkeleton(mesh.skeleton);
  24581. }
  24582. // Render targets
  24583. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24584. var needsRestoreFrameBuffer = false;
  24585. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24586. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24587. }
  24588. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24589. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24590. }
  24591. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24592. this._intermediateRendering = true;
  24593. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24594. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24595. var renderTarget = this._renderTargets.data[renderIndex];
  24596. if (renderTarget._shouldRender()) {
  24597. this._renderId++;
  24598. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24599. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24600. }
  24601. }
  24602. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24603. this._intermediateRendering = false;
  24604. this._renderId++;
  24605. needsRestoreFrameBuffer = true; // Restore back buffer
  24606. }
  24607. // Render EffecttLayer Texture
  24608. var stencilState = this._engine.getStencilBuffer();
  24609. var renderEffects = false;
  24610. var needStencil = false;
  24611. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24612. this._intermediateRendering = true;
  24613. for (var i = 0; i < this.effectLayers.length; i++) {
  24614. var effectLayer = this.effectLayers[i];
  24615. if (effectLayer.shouldRender() &&
  24616. (!effectLayer.camera ||
  24617. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24618. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24619. renderEffects = true;
  24620. needStencil = needStencil || effectLayer.needStencil();
  24621. var renderTarget = effectLayer._mainTexture;
  24622. if (renderTarget._shouldRender()) {
  24623. this._renderId++;
  24624. renderTarget.render(false, false);
  24625. needsRestoreFrameBuffer = true;
  24626. }
  24627. }
  24628. }
  24629. this._intermediateRendering = false;
  24630. this._renderId++;
  24631. }
  24632. if (needsRestoreFrameBuffer) {
  24633. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24634. }
  24635. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24636. // Prepare Frame
  24637. this.postProcessManager._prepareFrame();
  24638. // Backgrounds
  24639. var layerIndex;
  24640. var layer;
  24641. if (this.layers.length) {
  24642. engine.setDepthBuffer(false);
  24643. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24644. layer = this.layers[layerIndex];
  24645. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24646. layer.render();
  24647. }
  24648. }
  24649. engine.setDepthBuffer(true);
  24650. }
  24651. // Activate effect Layer stencil
  24652. if (needStencil) {
  24653. this._engine.setStencilBuffer(true);
  24654. }
  24655. // Render
  24656. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24657. this._renderingManager.render(null, null, true, true);
  24658. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24659. // Restore effect Layer stencil
  24660. if (needStencil) {
  24661. this._engine.setStencilBuffer(stencilState);
  24662. }
  24663. // Bounding boxes
  24664. if (this._boundingBoxRenderer) {
  24665. this._boundingBoxRenderer.render();
  24666. }
  24667. // Lens flares
  24668. if (this.lensFlaresEnabled) {
  24669. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24670. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24671. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24672. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24673. lensFlareSystem.render();
  24674. }
  24675. }
  24676. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24677. }
  24678. // Foregrounds
  24679. if (this.layers.length) {
  24680. engine.setDepthBuffer(false);
  24681. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24682. layer = this.layers[layerIndex];
  24683. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24684. layer.render();
  24685. }
  24686. }
  24687. engine.setDepthBuffer(true);
  24688. }
  24689. // Effect Layer
  24690. if (renderEffects) {
  24691. engine.setDepthBuffer(false);
  24692. for (var i = 0; i < this.effectLayers.length; i++) {
  24693. if (this.effectLayers[i].shouldRender()) {
  24694. this.effectLayers[i].render();
  24695. }
  24696. }
  24697. engine.setDepthBuffer(true);
  24698. }
  24699. // Finalize frame
  24700. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24701. // Reset some special arrays
  24702. this._renderTargets.reset();
  24703. this._alternateRendering = false;
  24704. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24705. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24706. };
  24707. Scene.prototype._processSubCameras = function (camera) {
  24708. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24709. this._renderForCamera(camera);
  24710. return;
  24711. }
  24712. // rig cameras
  24713. for (var index = 0; index < camera._rigCameras.length; index++) {
  24714. this._renderForCamera(camera._rigCameras[index], camera);
  24715. }
  24716. this.activeCamera = camera;
  24717. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24718. };
  24719. Scene.prototype._checkIntersections = function () {
  24720. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24721. var sourceMesh = this._meshesForIntersections.data[index];
  24722. if (!sourceMesh.actionManager) {
  24723. continue;
  24724. }
  24725. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24726. var action = sourceMesh.actionManager.actions[actionIndex];
  24727. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24728. var parameters = action.getTriggerParameter();
  24729. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24730. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24731. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24732. if (areIntersecting && currentIntersectionInProgress === -1) {
  24733. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24734. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24735. sourceMesh._intersectionsInProgress.push(otherMesh);
  24736. }
  24737. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24738. sourceMesh._intersectionsInProgress.push(otherMesh);
  24739. }
  24740. }
  24741. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24742. //They intersected, and now they don't.
  24743. //is this trigger an exit trigger? execute an event.
  24744. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24745. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24746. }
  24747. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24748. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24749. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24750. }
  24751. }
  24752. }
  24753. }
  24754. }
  24755. };
  24756. Scene.prototype.render = function () {
  24757. if (this.isDisposed) {
  24758. return;
  24759. }
  24760. this._activeParticles.fetchNewFrame();
  24761. this._totalVertices.fetchNewFrame();
  24762. this._activeIndices.fetchNewFrame();
  24763. this._activeBones.fetchNewFrame();
  24764. this._meshesForIntersections.reset();
  24765. this.resetCachedMaterial();
  24766. this.onBeforeAnimationsObservable.notifyObservers(this);
  24767. // Actions
  24768. if (this.actionManager) {
  24769. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24770. }
  24771. //Simplification Queue
  24772. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24773. this.simplificationQueue.executeNext();
  24774. }
  24775. if (this._engine.isDeterministicLockStep()) {
  24776. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24777. var defaultFPS = (60.0 / 1000.0);
  24778. var defaultFrameTime = 1000 / 60; // frame time in MS
  24779. if (this._physicsEngine) {
  24780. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24781. }
  24782. var stepsTaken = 0;
  24783. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24784. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24785. internalSteps = Math.min(internalSteps, maxSubSteps);
  24786. do {
  24787. this.onBeforeStepObservable.notifyObservers(this);
  24788. // Animations
  24789. this._animationRatio = defaultFrameTime * defaultFPS;
  24790. this._animate();
  24791. this.onAfterAnimationsObservable.notifyObservers(this);
  24792. // Physics
  24793. if (this._physicsEngine) {
  24794. this.onBeforePhysicsObservable.notifyObservers(this);
  24795. this._physicsEngine._step(defaultFrameTime / 1000);
  24796. this.onAfterPhysicsObservable.notifyObservers(this);
  24797. }
  24798. this.onAfterStepObservable.notifyObservers(this);
  24799. this._currentStepId++;
  24800. stepsTaken++;
  24801. deltaTime -= defaultFrameTime;
  24802. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24803. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24804. }
  24805. else {
  24806. // Animations
  24807. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24808. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24809. this._animate();
  24810. this.onAfterAnimationsObservable.notifyObservers(this);
  24811. // Physics
  24812. if (this._physicsEngine) {
  24813. this.onBeforePhysicsObservable.notifyObservers(this);
  24814. this._physicsEngine._step(deltaTime / 1000.0);
  24815. this.onAfterPhysicsObservable.notifyObservers(this);
  24816. }
  24817. }
  24818. // update gamepad manager
  24819. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24820. this._gamepadManager._checkGamepadsStatus();
  24821. }
  24822. // Update Cameras
  24823. if (this.activeCameras.length > 0) {
  24824. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24825. var camera = this.activeCameras[cameraIndex];
  24826. camera.update();
  24827. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24828. // rig cameras
  24829. for (var index = 0; index < camera._rigCameras.length; index++) {
  24830. camera._rigCameras[index].update();
  24831. }
  24832. }
  24833. }
  24834. }
  24835. else if (this.activeCamera) {
  24836. this.activeCamera.update();
  24837. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24838. // rig cameras
  24839. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24840. this.activeCamera._rigCameras[index].update();
  24841. }
  24842. }
  24843. }
  24844. // Before render
  24845. this.onBeforeRenderObservable.notifyObservers(this);
  24846. // Customs render targets
  24847. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24848. var engine = this.getEngine();
  24849. var currentActiveCamera = this.activeCamera;
  24850. if (this.renderTargetsEnabled) {
  24851. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24852. this._intermediateRendering = true;
  24853. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24854. var renderTarget = this.customRenderTargets[customIndex];
  24855. if (renderTarget._shouldRender()) {
  24856. this._renderId++;
  24857. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24858. if (!this.activeCamera)
  24859. throw new Error("Active camera not set");
  24860. // Viewport
  24861. engine.setViewport(this.activeCamera.viewport);
  24862. // Camera
  24863. this.updateTransformMatrix();
  24864. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24865. }
  24866. }
  24867. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24868. this._intermediateRendering = false;
  24869. this._renderId++;
  24870. }
  24871. // Restore back buffer
  24872. if (this.customRenderTargets.length > 0) {
  24873. engine.restoreDefaultFramebuffer();
  24874. }
  24875. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24876. this.activeCamera = currentActiveCamera;
  24877. // Procedural textures
  24878. if (this.proceduralTexturesEnabled) {
  24879. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24880. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24881. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24882. if (proceduralTexture._shouldRender()) {
  24883. proceduralTexture.render();
  24884. }
  24885. }
  24886. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24887. }
  24888. // Clear
  24889. if (this.autoClearDepthAndStencil || this.autoClear) {
  24890. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24891. }
  24892. // Shadows
  24893. if (this.shadowsEnabled) {
  24894. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24895. var light = this.lights[lightIndex];
  24896. var shadowGenerator = light.getShadowGenerator();
  24897. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24898. var shadowMap = (shadowGenerator.getShadowMap());
  24899. if (this.textures.indexOf(shadowMap) !== -1) {
  24900. this._renderTargets.push(shadowMap);
  24901. }
  24902. }
  24903. }
  24904. }
  24905. // Depth renderer
  24906. for (var key in this._depthRenderer) {
  24907. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24908. }
  24909. // Geometry renderer
  24910. if (this._geometryBufferRenderer) {
  24911. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24912. }
  24913. // RenderPipeline
  24914. if (this._postProcessRenderPipelineManager) {
  24915. this._postProcessRenderPipelineManager.update();
  24916. }
  24917. // Multi-cameras?
  24918. if (this.activeCameras.length > 0) {
  24919. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24920. if (cameraIndex > 0) {
  24921. this._engine.clear(null, false, true, true);
  24922. }
  24923. this._processSubCameras(this.activeCameras[cameraIndex]);
  24924. }
  24925. }
  24926. else {
  24927. if (!this.activeCamera) {
  24928. throw new Error("No camera defined");
  24929. }
  24930. this._processSubCameras(this.activeCamera);
  24931. }
  24932. // Intersection checks
  24933. this._checkIntersections();
  24934. // Update the audio listener attached to the camera
  24935. if (BABYLON.AudioEngine) {
  24936. this._updateAudioParameters();
  24937. }
  24938. // After render
  24939. if (this.afterRender) {
  24940. this.afterRender();
  24941. }
  24942. this.onAfterRenderObservable.notifyObservers(this);
  24943. // Cleaning
  24944. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24945. var data = this._toBeDisposed.data[index];
  24946. if (data) {
  24947. data.dispose();
  24948. }
  24949. this._toBeDisposed[index] = null;
  24950. }
  24951. this._toBeDisposed.reset();
  24952. if (this.dumpNextRenderTargets) {
  24953. this.dumpNextRenderTargets = false;
  24954. }
  24955. this._activeBones.addCount(0, true);
  24956. this._activeIndices.addCount(0, true);
  24957. this._activeParticles.addCount(0, true);
  24958. };
  24959. Scene.prototype._updateAudioParameters = function () {
  24960. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24961. return;
  24962. }
  24963. var listeningCamera;
  24964. var audioEngine = BABYLON.Engine.audioEngine;
  24965. if (this.activeCameras.length > 0) {
  24966. listeningCamera = this.activeCameras[0];
  24967. }
  24968. else {
  24969. listeningCamera = this.activeCamera;
  24970. }
  24971. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24972. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24973. // for VR cameras
  24974. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24975. listeningCamera = listeningCamera.rigCameras[0];
  24976. }
  24977. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24978. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24979. cameraDirection.normalize();
  24980. // To avoid some errors on GearVR
  24981. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24982. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24983. }
  24984. var i;
  24985. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24986. var sound = this.mainSoundTrack.soundCollection[i];
  24987. if (sound.useCustomAttenuation) {
  24988. sound.updateDistanceFromListener();
  24989. }
  24990. }
  24991. for (i = 0; i < this.soundTracks.length; i++) {
  24992. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24993. sound = this.soundTracks[i].soundCollection[j];
  24994. if (sound.useCustomAttenuation) {
  24995. sound.updateDistanceFromListener();
  24996. }
  24997. }
  24998. }
  24999. }
  25000. };
  25001. Object.defineProperty(Scene.prototype, "audioEnabled", {
  25002. // Audio
  25003. get: function () {
  25004. return this._audioEnabled;
  25005. },
  25006. set: function (value) {
  25007. this._audioEnabled = value;
  25008. if (BABYLON.AudioEngine) {
  25009. if (this._audioEnabled) {
  25010. this._enableAudio();
  25011. }
  25012. else {
  25013. this._disableAudio();
  25014. }
  25015. }
  25016. },
  25017. enumerable: true,
  25018. configurable: true
  25019. });
  25020. Scene.prototype._disableAudio = function () {
  25021. var i;
  25022. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25023. this.mainSoundTrack.soundCollection[i].pause();
  25024. }
  25025. for (i = 0; i < this.soundTracks.length; i++) {
  25026. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25027. this.soundTracks[i].soundCollection[j].pause();
  25028. }
  25029. }
  25030. };
  25031. Scene.prototype._enableAudio = function () {
  25032. var i;
  25033. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25034. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  25035. this.mainSoundTrack.soundCollection[i].play();
  25036. }
  25037. }
  25038. for (i = 0; i < this.soundTracks.length; i++) {
  25039. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25040. if (this.soundTracks[i].soundCollection[j].isPaused) {
  25041. this.soundTracks[i].soundCollection[j].play();
  25042. }
  25043. }
  25044. }
  25045. };
  25046. Object.defineProperty(Scene.prototype, "headphone", {
  25047. get: function () {
  25048. return this._headphone;
  25049. },
  25050. set: function (value) {
  25051. this._headphone = value;
  25052. if (BABYLON.AudioEngine) {
  25053. if (this._headphone) {
  25054. this._switchAudioModeForHeadphones();
  25055. }
  25056. else {
  25057. this._switchAudioModeForNormalSpeakers();
  25058. }
  25059. }
  25060. },
  25061. enumerable: true,
  25062. configurable: true
  25063. });
  25064. Scene.prototype._switchAudioModeForHeadphones = function () {
  25065. this.mainSoundTrack.switchPanningModelToHRTF();
  25066. for (var i = 0; i < this.soundTracks.length; i++) {
  25067. this.soundTracks[i].switchPanningModelToHRTF();
  25068. }
  25069. };
  25070. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  25071. this.mainSoundTrack.switchPanningModelToEqualPower();
  25072. for (var i = 0; i < this.soundTracks.length; i++) {
  25073. this.soundTracks[i].switchPanningModelToEqualPower();
  25074. }
  25075. };
  25076. /**
  25077. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  25078. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  25079. * @returns the created depth renderer
  25080. */
  25081. Scene.prototype.enableDepthRenderer = function (camera) {
  25082. camera = camera || this.activeCamera;
  25083. if (!camera) {
  25084. throw "No camera available to enable depth renderer";
  25085. }
  25086. if (!this._depthRenderer[camera.id]) {
  25087. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  25088. }
  25089. return this._depthRenderer[camera.id];
  25090. };
  25091. /**
  25092. * Disables a depth renderer for a given camera
  25093. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  25094. */
  25095. Scene.prototype.disableDepthRenderer = function (camera) {
  25096. camera = camera || this.activeCamera;
  25097. if (!camera || !this._depthRenderer[camera.id]) {
  25098. return;
  25099. }
  25100. this._depthRenderer[camera.id].dispose();
  25101. delete this._depthRenderer[camera.id];
  25102. };
  25103. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  25104. if (ratio === void 0) { ratio = 1; }
  25105. if (this._geometryBufferRenderer) {
  25106. return this._geometryBufferRenderer;
  25107. }
  25108. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  25109. if (!this._geometryBufferRenderer.isSupported) {
  25110. this._geometryBufferRenderer = null;
  25111. }
  25112. return this._geometryBufferRenderer;
  25113. };
  25114. Scene.prototype.disableGeometryBufferRenderer = function () {
  25115. if (!this._geometryBufferRenderer) {
  25116. return;
  25117. }
  25118. this._geometryBufferRenderer.dispose();
  25119. this._geometryBufferRenderer = null;
  25120. };
  25121. Scene.prototype.freezeMaterials = function () {
  25122. for (var i = 0; i < this.materials.length; i++) {
  25123. this.materials[i].freeze();
  25124. }
  25125. };
  25126. Scene.prototype.unfreezeMaterials = function () {
  25127. for (var i = 0; i < this.materials.length; i++) {
  25128. this.materials[i].unfreeze();
  25129. }
  25130. };
  25131. Scene.prototype.dispose = function () {
  25132. this.beforeRender = null;
  25133. this.afterRender = null;
  25134. this.skeletons = [];
  25135. this.morphTargetManagers = [];
  25136. this.importedMeshesFiles = new Array();
  25137. this.stopAllAnimations();
  25138. this.resetCachedMaterial();
  25139. for (var key in this._depthRenderer) {
  25140. this._depthRenderer[key].dispose();
  25141. }
  25142. if (this._gamepadManager) {
  25143. this._gamepadManager.dispose();
  25144. this._gamepadManager = null;
  25145. }
  25146. // Smart arrays
  25147. if (this.activeCamera) {
  25148. this.activeCamera._activeMeshes.dispose();
  25149. this.activeCamera = null;
  25150. }
  25151. this._activeMeshes.dispose();
  25152. this._renderingManager.dispose();
  25153. this._processedMaterials.dispose();
  25154. this._activeParticleSystems.dispose();
  25155. this._activeSkeletons.dispose();
  25156. this._softwareSkinnedMeshes.dispose();
  25157. this._renderTargets.dispose();
  25158. this._registeredForLateAnimationBindings.dispose();
  25159. if (this._boundingBoxRenderer) {
  25160. this._boundingBoxRenderer.dispose();
  25161. }
  25162. this._meshesForIntersections.dispose();
  25163. this._toBeDisposed.dispose();
  25164. // Abort active requests
  25165. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  25166. var request = _a[_i];
  25167. request.abort();
  25168. }
  25169. // Debug layer
  25170. if (this._debugLayer) {
  25171. this._debugLayer.hide();
  25172. }
  25173. // Events
  25174. this.onDisposeObservable.notifyObservers(this);
  25175. this.onDisposeObservable.clear();
  25176. this.onBeforeRenderObservable.clear();
  25177. this.onAfterRenderObservable.clear();
  25178. this.OnBeforeRenderTargetsRenderObservable.clear();
  25179. this.OnAfterRenderTargetsRenderObservable.clear();
  25180. this.onAfterStepObservable.clear();
  25181. this.onBeforeStepObservable.clear();
  25182. this.onBeforeActiveMeshesEvaluationObservable.clear();
  25183. this.onAfterActiveMeshesEvaluationObservable.clear();
  25184. this.onBeforeParticlesRenderingObservable.clear();
  25185. this.onAfterParticlesRenderingObservable.clear();
  25186. this.onBeforeSpritesRenderingObservable.clear();
  25187. this.onAfterSpritesRenderingObservable.clear();
  25188. this.onBeforeDrawPhaseObservable.clear();
  25189. this.onAfterDrawPhaseObservable.clear();
  25190. this.onBeforePhysicsObservable.clear();
  25191. this.onAfterPhysicsObservable.clear();
  25192. this.onBeforeAnimationsObservable.clear();
  25193. this.onAfterAnimationsObservable.clear();
  25194. this.onDataLoadedObservable.clear();
  25195. this.detachControl();
  25196. // Release sounds & sounds tracks
  25197. if (BABYLON.AudioEngine) {
  25198. this.disposeSounds();
  25199. }
  25200. // VR Helper
  25201. if (this.VRHelper) {
  25202. this.VRHelper.dispose();
  25203. }
  25204. // Detach cameras
  25205. var canvas = this._engine.getRenderingCanvas();
  25206. if (canvas) {
  25207. var index;
  25208. for (index = 0; index < this.cameras.length; index++) {
  25209. this.cameras[index].detachControl(canvas);
  25210. }
  25211. }
  25212. // Release animation groups
  25213. while (this.animationGroups.length) {
  25214. this.animationGroups[0].dispose();
  25215. }
  25216. // Release lights
  25217. while (this.lights.length) {
  25218. this.lights[0].dispose();
  25219. }
  25220. // Release meshes
  25221. while (this.meshes.length) {
  25222. this.meshes[0].dispose(true);
  25223. }
  25224. while (this.transformNodes.length) {
  25225. this.removeTransformNode(this.transformNodes[0]);
  25226. }
  25227. // Release cameras
  25228. while (this.cameras.length) {
  25229. this.cameras[0].dispose();
  25230. }
  25231. // Release materials
  25232. if (this.defaultMaterial) {
  25233. this.defaultMaterial.dispose();
  25234. }
  25235. while (this.multiMaterials.length) {
  25236. this.multiMaterials[0].dispose();
  25237. }
  25238. while (this.materials.length) {
  25239. this.materials[0].dispose();
  25240. }
  25241. // Release particles
  25242. while (this.particleSystems.length) {
  25243. this.particleSystems[0].dispose();
  25244. }
  25245. // Release sprites
  25246. while (this.spriteManagers.length) {
  25247. this.spriteManagers[0].dispose();
  25248. }
  25249. // Release postProcesses
  25250. while (this.postProcesses.length) {
  25251. this.postProcesses[0].dispose();
  25252. }
  25253. // Release layers
  25254. while (this.layers.length) {
  25255. this.layers[0].dispose();
  25256. }
  25257. while (this.effectLayers.length) {
  25258. this.effectLayers[0].dispose();
  25259. }
  25260. // Release textures
  25261. while (this.textures.length) {
  25262. this.textures[0].dispose();
  25263. }
  25264. // Release UBO
  25265. this._sceneUbo.dispose();
  25266. if (this._alternateSceneUbo) {
  25267. this._alternateSceneUbo.dispose();
  25268. }
  25269. // Post-processes
  25270. this.postProcessManager.dispose();
  25271. if (this._postProcessRenderPipelineManager) {
  25272. this._postProcessRenderPipelineManager.dispose();
  25273. }
  25274. // Physics
  25275. if (this._physicsEngine) {
  25276. this.disablePhysicsEngine();
  25277. }
  25278. // Remove from engine
  25279. index = this._engine.scenes.indexOf(this);
  25280. if (index > -1) {
  25281. this._engine.scenes.splice(index, 1);
  25282. }
  25283. this._engine.wipeCaches(true);
  25284. this._isDisposed = true;
  25285. };
  25286. Object.defineProperty(Scene.prototype, "isDisposed", {
  25287. get: function () {
  25288. return this._isDisposed;
  25289. },
  25290. enumerable: true,
  25291. configurable: true
  25292. });
  25293. // Release sounds & sounds tracks
  25294. Scene.prototype.disposeSounds = function () {
  25295. if (!this._mainSoundTrack) {
  25296. return;
  25297. }
  25298. this.mainSoundTrack.dispose();
  25299. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25300. this.soundTracks[scIndex].dispose();
  25301. }
  25302. };
  25303. // Octrees
  25304. /**
  25305. * Get the world extend vectors with an optional filter
  25306. *
  25307. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25308. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25309. */
  25310. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25311. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25312. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25313. filterPredicate = filterPredicate || (function () { return true; });
  25314. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25315. mesh.computeWorldMatrix(true);
  25316. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25317. return;
  25318. }
  25319. var boundingInfo = mesh.getBoundingInfo();
  25320. var minBox = boundingInfo.boundingBox.minimumWorld;
  25321. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25322. BABYLON.Tools.CheckExtends(minBox, min, max);
  25323. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25324. });
  25325. return {
  25326. min: min,
  25327. max: max
  25328. };
  25329. };
  25330. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25331. if (maxCapacity === void 0) { maxCapacity = 64; }
  25332. if (maxDepth === void 0) { maxDepth = 2; }
  25333. if (!this._selectionOctree) {
  25334. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25335. }
  25336. var worldExtends = this.getWorldExtends();
  25337. // Update octree
  25338. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25339. return this._selectionOctree;
  25340. };
  25341. // Picking
  25342. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25343. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25344. var result = BABYLON.Ray.Zero();
  25345. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25346. return result;
  25347. };
  25348. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25349. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25350. var engine = this._engine;
  25351. if (!camera) {
  25352. if (!this.activeCamera)
  25353. throw new Error("Active camera not set");
  25354. camera = this.activeCamera;
  25355. }
  25356. var cameraViewport = camera.viewport;
  25357. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25358. // Moving coordinates to local viewport world
  25359. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25360. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25361. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25362. return this;
  25363. };
  25364. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25365. var result = BABYLON.Ray.Zero();
  25366. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25367. return result;
  25368. };
  25369. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25370. if (!BABYLON.PickingInfo) {
  25371. return this;
  25372. }
  25373. var engine = this._engine;
  25374. if (!camera) {
  25375. if (!this.activeCamera)
  25376. throw new Error("Active camera not set");
  25377. camera = this.activeCamera;
  25378. }
  25379. var cameraViewport = camera.viewport;
  25380. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25381. var identity = BABYLON.Matrix.Identity();
  25382. // Moving coordinates to local viewport world
  25383. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25384. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25385. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25386. return this;
  25387. };
  25388. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25389. if (!BABYLON.PickingInfo) {
  25390. return null;
  25391. }
  25392. var pickingInfo = null;
  25393. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25394. var mesh = this.meshes[meshIndex];
  25395. if (predicate) {
  25396. if (!predicate(mesh)) {
  25397. continue;
  25398. }
  25399. }
  25400. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25401. continue;
  25402. }
  25403. var world = mesh.getWorldMatrix();
  25404. var ray = rayFunction(world);
  25405. var result = mesh.intersects(ray, fastCheck);
  25406. if (!result || !result.hit)
  25407. continue;
  25408. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25409. continue;
  25410. pickingInfo = result;
  25411. if (fastCheck) {
  25412. break;
  25413. }
  25414. }
  25415. return pickingInfo || new BABYLON.PickingInfo();
  25416. };
  25417. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25418. if (!BABYLON.PickingInfo) {
  25419. return null;
  25420. }
  25421. var pickingInfos = new Array();
  25422. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25423. var mesh = this.meshes[meshIndex];
  25424. if (predicate) {
  25425. if (!predicate(mesh)) {
  25426. continue;
  25427. }
  25428. }
  25429. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25430. continue;
  25431. }
  25432. var world = mesh.getWorldMatrix();
  25433. var ray = rayFunction(world);
  25434. var result = mesh.intersects(ray, false);
  25435. if (!result || !result.hit)
  25436. continue;
  25437. pickingInfos.push(result);
  25438. }
  25439. return pickingInfos;
  25440. };
  25441. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25442. if (!BABYLON.PickingInfo) {
  25443. return null;
  25444. }
  25445. var pickingInfo = null;
  25446. if (!camera) {
  25447. if (!this.activeCamera) {
  25448. return null;
  25449. }
  25450. camera = this.activeCamera;
  25451. }
  25452. if (this.spriteManagers.length > 0) {
  25453. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25454. var spriteManager = this.spriteManagers[spriteIndex];
  25455. if (!spriteManager.isPickable) {
  25456. continue;
  25457. }
  25458. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25459. if (!result || !result.hit)
  25460. continue;
  25461. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25462. continue;
  25463. pickingInfo = result;
  25464. if (fastCheck) {
  25465. break;
  25466. }
  25467. }
  25468. }
  25469. return pickingInfo || new BABYLON.PickingInfo();
  25470. };
  25471. /** Launch a ray to try to pick a mesh in the scene
  25472. * @param x position on screen
  25473. * @param y position on screen
  25474. * @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
  25475. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25476. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25477. */
  25478. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25479. var _this = this;
  25480. if (!BABYLON.PickingInfo) {
  25481. return null;
  25482. }
  25483. return this._internalPick(function (world) {
  25484. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25485. return _this._tempPickingRay;
  25486. }, predicate, fastCheck);
  25487. };
  25488. /** Launch a ray to try to pick a sprite in the scene
  25489. * @param x position on screen
  25490. * @param y position on screen
  25491. * @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
  25492. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25493. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25494. */
  25495. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25496. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25497. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25498. };
  25499. /** Use the given ray to pick a mesh in the scene
  25500. * @param ray The ray to use to pick meshes
  25501. * @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
  25502. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25503. */
  25504. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25505. var _this = this;
  25506. return this._internalPick(function (world) {
  25507. if (!_this._pickWithRayInverseMatrix) {
  25508. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25509. }
  25510. world.invertToRef(_this._pickWithRayInverseMatrix);
  25511. if (!_this._cachedRayForTransform) {
  25512. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25513. }
  25514. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25515. return _this._cachedRayForTransform;
  25516. }, predicate, fastCheck);
  25517. };
  25518. /**
  25519. * Launch a ray to try to pick a mesh in the scene
  25520. * @param x X position on screen
  25521. * @param y Y position on screen
  25522. * @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
  25523. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25524. */
  25525. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25526. var _this = this;
  25527. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25528. };
  25529. /**
  25530. * Launch a ray to try to pick a mesh in the scene
  25531. * @param ray Ray to use
  25532. * @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
  25533. */
  25534. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25535. var _this = this;
  25536. return this._internalMultiPick(function (world) {
  25537. if (!_this._pickWithRayInverseMatrix) {
  25538. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25539. }
  25540. world.invertToRef(_this._pickWithRayInverseMatrix);
  25541. if (!_this._cachedRayForTransform) {
  25542. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25543. }
  25544. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25545. return _this._cachedRayForTransform;
  25546. }, predicate);
  25547. };
  25548. Scene.prototype.setPointerOverMesh = function (mesh) {
  25549. if (this._pointerOverMesh === mesh) {
  25550. return;
  25551. }
  25552. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25553. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25554. }
  25555. this._pointerOverMesh = mesh;
  25556. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25557. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25558. }
  25559. };
  25560. Scene.prototype.getPointerOverMesh = function () {
  25561. return this._pointerOverMesh;
  25562. };
  25563. Scene.prototype.setPointerOverSprite = function (sprite) {
  25564. if (this._pointerOverSprite === sprite) {
  25565. return;
  25566. }
  25567. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25568. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25569. }
  25570. this._pointerOverSprite = sprite;
  25571. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25572. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25573. }
  25574. };
  25575. Scene.prototype.getPointerOverSprite = function () {
  25576. return this._pointerOverSprite;
  25577. };
  25578. // Physics
  25579. Scene.prototype.getPhysicsEngine = function () {
  25580. return this._physicsEngine;
  25581. };
  25582. /**
  25583. * Enables physics to the current scene
  25584. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25585. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25586. * @return {boolean} was the physics engine initialized
  25587. */
  25588. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25589. if (gravity === void 0) { gravity = null; }
  25590. if (this._physicsEngine) {
  25591. return true;
  25592. }
  25593. try {
  25594. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25595. return true;
  25596. }
  25597. catch (e) {
  25598. BABYLON.Tools.Error(e.message);
  25599. return false;
  25600. }
  25601. };
  25602. Scene.prototype.disablePhysicsEngine = function () {
  25603. if (!this._physicsEngine) {
  25604. return;
  25605. }
  25606. this._physicsEngine.dispose();
  25607. this._physicsEngine = null;
  25608. };
  25609. Scene.prototype.isPhysicsEnabled = function () {
  25610. return this._physicsEngine !== undefined;
  25611. };
  25612. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25613. var mesh = compound.parts[0].mesh;
  25614. if (mesh.physicsImpostor) {
  25615. mesh.physicsImpostor.dispose();
  25616. mesh.physicsImpostor = null;
  25617. }
  25618. };
  25619. // Misc.
  25620. Scene.prototype._rebuildGeometries = function () {
  25621. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25622. var geometry = _a[_i];
  25623. geometry._rebuild();
  25624. }
  25625. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25626. var mesh = _c[_b];
  25627. mesh._rebuild();
  25628. }
  25629. if (this.postProcessManager) {
  25630. this.postProcessManager._rebuild();
  25631. }
  25632. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25633. var layer = _e[_d];
  25634. layer._rebuild();
  25635. }
  25636. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25637. var effectLayer = _g[_f];
  25638. effectLayer._rebuild();
  25639. }
  25640. if (this._boundingBoxRenderer) {
  25641. this._boundingBoxRenderer._rebuild();
  25642. }
  25643. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25644. var system = _j[_h];
  25645. system.rebuild();
  25646. }
  25647. if (this._postProcessRenderPipelineManager) {
  25648. this._postProcessRenderPipelineManager._rebuild();
  25649. }
  25650. };
  25651. Scene.prototype._rebuildTextures = function () {
  25652. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25653. var texture = _a[_i];
  25654. texture._rebuild();
  25655. }
  25656. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25657. };
  25658. /**
  25659. * Creates a default light for the scene.
  25660. * @param replace Whether to replace the existing lights in the scene.
  25661. */
  25662. Scene.prototype.createDefaultLight = function (replace) {
  25663. if (replace === void 0) { replace = false; }
  25664. // Dispose existing light in replace mode.
  25665. if (replace) {
  25666. if (this.lights) {
  25667. for (var i = 0; i < this.lights.length; i++) {
  25668. this.lights[i].dispose();
  25669. }
  25670. }
  25671. }
  25672. // Light
  25673. if (this.lights.length === 0) {
  25674. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25675. }
  25676. };
  25677. /**
  25678. * Creates a default camera for the scene.
  25679. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25680. * @param replace Whether to replace the existing active camera in the scene.
  25681. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25682. */
  25683. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25684. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25685. if (replace === void 0) { replace = false; }
  25686. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25687. // Dispose existing camera in replace mode.
  25688. if (replace) {
  25689. if (this.activeCamera) {
  25690. this.activeCamera.dispose();
  25691. this.activeCamera = null;
  25692. }
  25693. }
  25694. // Camera
  25695. if (!this.activeCamera) {
  25696. var worldExtends = this.getWorldExtends();
  25697. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25698. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25699. var camera;
  25700. var radius = worldSize.length() * 1.5;
  25701. // empty scene scenario!
  25702. if (!isFinite(radius)) {
  25703. radius = 1;
  25704. worldCenter.copyFromFloats(0, 0, 0);
  25705. }
  25706. if (createArcRotateCamera) {
  25707. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25708. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25709. arcRotateCamera.wheelPrecision = 100 / radius;
  25710. camera = arcRotateCamera;
  25711. }
  25712. else {
  25713. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25714. freeCamera.setTarget(worldCenter);
  25715. camera = freeCamera;
  25716. }
  25717. camera.minZ = radius * 0.01;
  25718. camera.maxZ = radius * 1000;
  25719. camera.speed = radius * 0.2;
  25720. this.activeCamera = camera;
  25721. var canvas = this.getEngine().getRenderingCanvas();
  25722. if (attachCameraControls && canvas) {
  25723. camera.attachControl(canvas);
  25724. }
  25725. }
  25726. };
  25727. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25728. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25729. if (replace === void 0) { replace = false; }
  25730. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25731. this.createDefaultLight(replace);
  25732. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25733. };
  25734. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25735. if (pbr === void 0) { pbr = false; }
  25736. if (scale === void 0) { scale = 1000; }
  25737. if (blur === void 0) { blur = 0; }
  25738. if (environmentTexture) {
  25739. this.environmentTexture = environmentTexture;
  25740. }
  25741. if (!this.environmentTexture) {
  25742. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25743. return null;
  25744. }
  25745. // Skybox
  25746. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25747. if (pbr) {
  25748. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25749. hdrSkyboxMaterial.backFaceCulling = false;
  25750. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25751. if (hdrSkyboxMaterial.reflectionTexture) {
  25752. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25753. }
  25754. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25755. hdrSkyboxMaterial.disableLighting = true;
  25756. hdrSkyboxMaterial.twoSidedLighting = true;
  25757. hdrSkybox.infiniteDistance = true;
  25758. hdrSkybox.material = hdrSkyboxMaterial;
  25759. }
  25760. else {
  25761. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25762. skyboxMaterial.backFaceCulling = false;
  25763. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25764. if (skyboxMaterial.reflectionTexture) {
  25765. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25766. }
  25767. skyboxMaterial.disableLighting = true;
  25768. hdrSkybox.infiniteDistance = true;
  25769. hdrSkybox.material = skyboxMaterial;
  25770. }
  25771. return hdrSkybox;
  25772. };
  25773. Scene.prototype.createDefaultEnvironment = function (options) {
  25774. if (BABYLON.EnvironmentHelper) {
  25775. return new BABYLON.EnvironmentHelper(options, this);
  25776. }
  25777. return null;
  25778. };
  25779. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25780. if (webVROptions === void 0) { webVROptions = {}; }
  25781. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25782. };
  25783. // Tags
  25784. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25785. if (tagsQuery === undefined) {
  25786. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25787. return list;
  25788. }
  25789. var listByTags = [];
  25790. forEach = forEach || (function (item) { return; });
  25791. for (var i in list) {
  25792. var item = list[i];
  25793. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25794. listByTags.push(item);
  25795. forEach(item);
  25796. }
  25797. }
  25798. return listByTags;
  25799. };
  25800. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25801. return this._getByTags(this.meshes, tagsQuery, forEach);
  25802. };
  25803. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25804. return this._getByTags(this.cameras, tagsQuery, forEach);
  25805. };
  25806. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25807. return this._getByTags(this.lights, tagsQuery, forEach);
  25808. };
  25809. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25810. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25811. };
  25812. /**
  25813. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25814. * This allowed control for front to back rendering or reversly depending of the special needs.
  25815. *
  25816. * @param renderingGroupId The rendering group id corresponding to its index
  25817. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25818. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25819. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25820. */
  25821. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25822. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25823. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25824. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25825. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25826. };
  25827. /**
  25828. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25829. *
  25830. * @param renderingGroupId The rendering group id corresponding to its index
  25831. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25832. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25833. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25834. */
  25835. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25836. if (depth === void 0) { depth = true; }
  25837. if (stencil === void 0) { stencil = true; }
  25838. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25839. };
  25840. /**
  25841. * Will flag all materials as dirty to trigger new shader compilation
  25842. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25843. */
  25844. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25845. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25846. var material = _a[_i];
  25847. if (predicate && !predicate(material)) {
  25848. continue;
  25849. }
  25850. material.markAsDirty(flag);
  25851. }
  25852. };
  25853. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25854. var _this = this;
  25855. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25856. this._activeRequests.push(request);
  25857. request.onCompleteObservable.add(function (request) {
  25858. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25859. });
  25860. return request;
  25861. };
  25862. /** @ignore */
  25863. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25864. var _this = this;
  25865. return new Promise(function (resolve, reject) {
  25866. _this._loadFile(url, function (data) {
  25867. resolve(data);
  25868. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25869. reject(exception);
  25870. });
  25871. });
  25872. };
  25873. // Statics
  25874. Scene._FOGMODE_NONE = 0;
  25875. Scene._FOGMODE_EXP = 1;
  25876. Scene._FOGMODE_EXP2 = 2;
  25877. Scene._FOGMODE_LINEAR = 3;
  25878. Scene._uniqueIdCounter = 0;
  25879. Scene.MinDeltaTime = 1.0;
  25880. Scene.MaxDeltaTime = 1000.0;
  25881. /** The distance in pixel that you have to move to prevent some events */
  25882. Scene.DragMovementThreshold = 10; // in pixels
  25883. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25884. Scene.LongPressDelay = 500; // in milliseconds
  25885. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25886. Scene.DoubleClickDelay = 300; // in milliseconds
  25887. /** If you need to check double click without raising a single click at first click, enable this flag */
  25888. Scene.ExclusiveDoubleClickMode = false;
  25889. return Scene;
  25890. }());
  25891. BABYLON.Scene = Scene;
  25892. })(BABYLON || (BABYLON = {}));
  25893. //# sourceMappingURL=babylon.scene.js.map
  25894. "use strict";
  25895. var BABYLON;
  25896. (function (BABYLON) {
  25897. /**
  25898. * Set of assets to keep when moving a scene into an asset container.
  25899. */
  25900. var KeepAssets = /** @class */ (function () {
  25901. function KeepAssets() {
  25902. /**
  25903. * Cameras to keep.
  25904. */
  25905. this.cameras = new Array();
  25906. /**
  25907. * Lights to keep.
  25908. */
  25909. this.lights = new Array();
  25910. /**
  25911. * Meshes to keep.
  25912. */
  25913. this.meshes = new Array();
  25914. /**
  25915. * Skeletons to keep.
  25916. */
  25917. this.skeletons = new Array();
  25918. /**
  25919. * ParticleSystems to keep.
  25920. */
  25921. this.particleSystems = new Array();
  25922. /**
  25923. * Animations to keep.
  25924. */
  25925. this.animations = new Array();
  25926. /**
  25927. * MultiMaterials to keep.
  25928. */
  25929. this.multiMaterials = new Array();
  25930. /**
  25931. * Materials to keep.
  25932. */
  25933. this.materials = new Array();
  25934. /**
  25935. * MorphTargetManagers to keep.
  25936. */
  25937. this.morphTargetManagers = new Array();
  25938. /**
  25939. * Geometries to keep.
  25940. */
  25941. this.geometries = new Array();
  25942. /**
  25943. * TransformNodes to keep.
  25944. */
  25945. this.transformNodes = new Array();
  25946. /**
  25947. * LensFlareSystems to keep.
  25948. */
  25949. this.lensFlareSystems = new Array();
  25950. /**
  25951. * ShadowGenerators to keep.
  25952. */
  25953. this.shadowGenerators = new Array();
  25954. /**
  25955. * ActionManagers to keep.
  25956. */
  25957. this.actionManagers = new Array();
  25958. /**
  25959. * Sounds to keep.
  25960. */
  25961. this.sounds = new Array();
  25962. }
  25963. return KeepAssets;
  25964. }());
  25965. BABYLON.KeepAssets = KeepAssets;
  25966. /**
  25967. * Container with a set of assets that can be added or removed from a scene.
  25968. */
  25969. var AssetContainer = /** @class */ (function () {
  25970. /**
  25971. * Instantiates an AssetContainer.
  25972. * @param scene The scene the AssetContainer belongs to.
  25973. */
  25974. function AssetContainer(scene) {
  25975. // Objects
  25976. /**
  25977. * Cameras populated in the container.
  25978. */
  25979. this.cameras = new Array();
  25980. /**
  25981. * Lights populated in the container.
  25982. */
  25983. this.lights = new Array();
  25984. /**
  25985. * Meshes populated in the container.
  25986. */
  25987. this.meshes = new Array();
  25988. /**
  25989. * Skeletons populated in the container.
  25990. */
  25991. this.skeletons = new Array();
  25992. /**
  25993. * ParticleSystems populated in the container.
  25994. */
  25995. this.particleSystems = new Array();
  25996. /**
  25997. * Animations populated in the container.
  25998. */
  25999. this.animations = new Array();
  26000. /**
  26001. * MultiMaterials populated in the container.
  26002. */
  26003. this.multiMaterials = new Array();
  26004. /**
  26005. * Materials populated in the container.
  26006. */
  26007. this.materials = new Array();
  26008. /**
  26009. * MorphTargetManagers populated in the container.
  26010. */
  26011. this.morphTargetManagers = new Array();
  26012. /**
  26013. * Geometries populated in the container.
  26014. */
  26015. this.geometries = new Array();
  26016. /**
  26017. * TransformNodes populated in the container.
  26018. */
  26019. this.transformNodes = new Array();
  26020. /**
  26021. * LensFlareSystems populated in the container.
  26022. */
  26023. this.lensFlareSystems = new Array();
  26024. /**
  26025. * ShadowGenerators populated in the container.
  26026. */
  26027. this.shadowGenerators = new Array();
  26028. /**
  26029. * ActionManagers populated in the container.
  26030. */
  26031. this.actionManagers = new Array();
  26032. /**
  26033. * Sounds populated in the container.
  26034. */
  26035. this.sounds = new Array();
  26036. this.scene = scene;
  26037. }
  26038. /**
  26039. * Adds all the assets from the container to the scene.
  26040. */
  26041. AssetContainer.prototype.addAllToScene = function () {
  26042. var _this = this;
  26043. this.cameras.forEach(function (o) {
  26044. _this.scene.addCamera(o);
  26045. });
  26046. this.lights.forEach(function (o) {
  26047. _this.scene.addLight(o);
  26048. });
  26049. this.meshes.forEach(function (o) {
  26050. _this.scene.addMesh(o);
  26051. });
  26052. this.skeletons.forEach(function (o) {
  26053. _this.scene.addSkeleton(o);
  26054. });
  26055. this.particleSystems.forEach(function (o) {
  26056. _this.scene.addParticleSystem(o);
  26057. });
  26058. this.animations.forEach(function (o) {
  26059. _this.scene.addAnimation(o);
  26060. });
  26061. this.multiMaterials.forEach(function (o) {
  26062. _this.scene.addMultiMaterial(o);
  26063. });
  26064. this.materials.forEach(function (o) {
  26065. _this.scene.addMaterial(o);
  26066. });
  26067. this.morphTargetManagers.forEach(function (o) {
  26068. _this.scene.addMorphTargetManager(o);
  26069. });
  26070. this.geometries.forEach(function (o) {
  26071. _this.scene.addGeometry(o);
  26072. });
  26073. this.transformNodes.forEach(function (o) {
  26074. _this.scene.addTransformNode(o);
  26075. });
  26076. this.lensFlareSystems.forEach(function (o) {
  26077. _this.scene.addLensFlareSystem(o);
  26078. });
  26079. this.actionManagers.forEach(function (o) {
  26080. _this.scene.addActionManager(o);
  26081. });
  26082. this.sounds.forEach(function (o) {
  26083. o.play();
  26084. o.autoplay = true;
  26085. _this.scene.mainSoundTrack.AddSound(o);
  26086. });
  26087. };
  26088. /**
  26089. * Removes all the assets in the container from the scene
  26090. */
  26091. AssetContainer.prototype.removeAllFromScene = function () {
  26092. var _this = this;
  26093. this.cameras.forEach(function (o) {
  26094. _this.scene.removeCamera(o);
  26095. });
  26096. this.lights.forEach(function (o) {
  26097. _this.scene.removeLight(o);
  26098. });
  26099. this.meshes.forEach(function (o) {
  26100. _this.scene.removeMesh(o);
  26101. });
  26102. this.skeletons.forEach(function (o) {
  26103. _this.scene.removeSkeleton(o);
  26104. });
  26105. this.particleSystems.forEach(function (o) {
  26106. _this.scene.removeParticleSystem(o);
  26107. });
  26108. this.animations.forEach(function (o) {
  26109. _this.scene.removeAnimation(o);
  26110. });
  26111. this.multiMaterials.forEach(function (o) {
  26112. _this.scene.removeMultiMaterial(o);
  26113. });
  26114. this.materials.forEach(function (o) {
  26115. _this.scene.removeMaterial(o);
  26116. });
  26117. this.morphTargetManagers.forEach(function (o) {
  26118. _this.scene.removeMorphTargetManager(o);
  26119. });
  26120. this.geometries.forEach(function (o) {
  26121. _this.scene.removeGeometry(o);
  26122. });
  26123. this.transformNodes.forEach(function (o) {
  26124. _this.scene.removeTransformNode(o);
  26125. });
  26126. this.lensFlareSystems.forEach(function (o) {
  26127. _this.scene.removeLensFlareSystem(o);
  26128. });
  26129. this.actionManagers.forEach(function (o) {
  26130. _this.scene.removeActionManager(o);
  26131. });
  26132. this.sounds.forEach(function (o) {
  26133. o.stop();
  26134. o.autoplay = false;
  26135. _this.scene.mainSoundTrack.RemoveSound(o);
  26136. });
  26137. };
  26138. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  26139. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  26140. var asset = sourceAssets_1[_i];
  26141. var move = true;
  26142. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  26143. var keepAsset = keepAssets_1[_a];
  26144. if (asset === keepAsset) {
  26145. move = false;
  26146. break;
  26147. }
  26148. }
  26149. if (move) {
  26150. targetAssets.push(asset);
  26151. }
  26152. }
  26153. };
  26154. /**
  26155. * Removes all the assets contained in the scene and adds them to the container.
  26156. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  26157. */
  26158. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  26159. if (keepAssets === undefined) {
  26160. keepAssets = new KeepAssets();
  26161. }
  26162. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  26163. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  26164. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  26165. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  26166. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  26167. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  26168. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  26169. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  26170. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  26171. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  26172. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  26173. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  26174. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  26175. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  26176. this.removeAllFromScene();
  26177. };
  26178. return AssetContainer;
  26179. }());
  26180. BABYLON.AssetContainer = AssetContainer;
  26181. })(BABYLON || (BABYLON = {}));
  26182. //# sourceMappingURL=babylon.assetContainer.js.map
  26183. "use strict";
  26184. var BABYLON;
  26185. (function (BABYLON) {
  26186. var Buffer = /** @class */ (function () {
  26187. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  26188. if (instanced === void 0) { instanced = false; }
  26189. if (engine instanceof BABYLON.Mesh) {
  26190. this._engine = engine.getScene().getEngine();
  26191. }
  26192. else {
  26193. this._engine = engine;
  26194. }
  26195. this._updatable = updatable;
  26196. this._instanced = instanced;
  26197. this._data = data;
  26198. this._strideSize = stride;
  26199. if (!postponeInternalCreation) {
  26200. this.create();
  26201. }
  26202. }
  26203. /**
  26204. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  26205. * @param kind defines the vertex buffer kind (position, normal, etc.)
  26206. * @param offset defines offset in the buffer (0 by default)
  26207. * @param size defines the size in floats of attributes (position is 3 for instance)
  26208. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  26209. * @param instanced defines if the vertex buffer contains indexed data
  26210. * @returns the new vertex buffer
  26211. */
  26212. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  26213. // a lot of these parameters are ignored as they are overriden by the buffer
  26214. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  26215. };
  26216. // Properties
  26217. Buffer.prototype.isUpdatable = function () {
  26218. return this._updatable;
  26219. };
  26220. Buffer.prototype.getData = function () {
  26221. return this._data;
  26222. };
  26223. Buffer.prototype.getBuffer = function () {
  26224. return this._buffer;
  26225. };
  26226. Buffer.prototype.getStrideSize = function () {
  26227. return this._strideSize;
  26228. };
  26229. // public getIsInstanced(): boolean {
  26230. // return this._instanced;
  26231. // }
  26232. // public get instanceDivisor(): number {
  26233. // return this._instanceDivisor;
  26234. // }
  26235. // public set instanceDivisor(value: number) {
  26236. // this._instanceDivisor = value;
  26237. // if (value == 0) {
  26238. // this._instanced = false;
  26239. // } else {
  26240. // this._instanced = true;
  26241. // }
  26242. // }
  26243. // Methods
  26244. Buffer.prototype.create = function (data) {
  26245. if (data === void 0) { data = null; }
  26246. if (!data && this._buffer) {
  26247. return; // nothing to do
  26248. }
  26249. data = data || this._data;
  26250. if (!data) {
  26251. return;
  26252. }
  26253. if (!this._buffer) {
  26254. if (this._updatable) {
  26255. this._buffer = this._engine.createDynamicVertexBuffer(data);
  26256. this._data = data;
  26257. }
  26258. else {
  26259. this._buffer = this._engine.createVertexBuffer(data);
  26260. }
  26261. }
  26262. else if (this._updatable) {
  26263. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  26264. this._data = data;
  26265. }
  26266. };
  26267. Buffer.prototype._rebuild = function () {
  26268. this._buffer = null;
  26269. this.create(this._data);
  26270. };
  26271. Buffer.prototype.update = function (data) {
  26272. this.create(data);
  26273. };
  26274. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  26275. if (!this._buffer) {
  26276. return;
  26277. }
  26278. if (this._updatable) {
  26279. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  26280. this._data = null;
  26281. }
  26282. };
  26283. Buffer.prototype.dispose = function () {
  26284. if (!this._buffer) {
  26285. return;
  26286. }
  26287. if (this._engine._releaseBuffer(this._buffer)) {
  26288. this._buffer = null;
  26289. }
  26290. };
  26291. return Buffer;
  26292. }());
  26293. BABYLON.Buffer = Buffer;
  26294. })(BABYLON || (BABYLON = {}));
  26295. //# sourceMappingURL=babylon.buffer.js.map
  26296. "use strict";
  26297. var BABYLON;
  26298. (function (BABYLON) {
  26299. var VertexBuffer = /** @class */ (function () {
  26300. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  26301. if (data instanceof BABYLON.Buffer) {
  26302. if (!stride) {
  26303. stride = data.getStrideSize();
  26304. }
  26305. this._buffer = data;
  26306. this._ownsBuffer = false;
  26307. }
  26308. else {
  26309. if (!stride) {
  26310. stride = VertexBuffer.DeduceStride(kind);
  26311. }
  26312. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  26313. this._ownsBuffer = true;
  26314. }
  26315. this._stride = stride;
  26316. this._instanced = instanced !== undefined ? instanced : false;
  26317. this._instanceDivisor = instanced ? 1 : 0;
  26318. this._offset = offset ? offset : 0;
  26319. this._size = size ? size : stride;
  26320. this._kind = kind;
  26321. }
  26322. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  26323. /**
  26324. * Gets or sets the instance divisor when in instanced mode
  26325. */
  26326. get: function () {
  26327. return this._instanceDivisor;
  26328. },
  26329. set: function (value) {
  26330. this._instanceDivisor = value;
  26331. if (value == 0) {
  26332. this._instanced = false;
  26333. }
  26334. else {
  26335. this._instanced = true;
  26336. }
  26337. },
  26338. enumerable: true,
  26339. configurable: true
  26340. });
  26341. VertexBuffer.prototype._rebuild = function () {
  26342. if (!this._buffer) {
  26343. return;
  26344. }
  26345. this._buffer._rebuild();
  26346. };
  26347. /**
  26348. * Returns the kind of the VertexBuffer (string).
  26349. */
  26350. VertexBuffer.prototype.getKind = function () {
  26351. return this._kind;
  26352. };
  26353. // Properties
  26354. /**
  26355. * Boolean : is the VertexBuffer updatable ?
  26356. */
  26357. VertexBuffer.prototype.isUpdatable = function () {
  26358. return this._buffer.isUpdatable();
  26359. };
  26360. /**
  26361. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26362. */
  26363. VertexBuffer.prototype.getData = function () {
  26364. return this._buffer.getData();
  26365. };
  26366. /**
  26367. * Returns the WebGLBuffer associated to the VertexBuffer.
  26368. */
  26369. VertexBuffer.prototype.getBuffer = function () {
  26370. return this._buffer.getBuffer();
  26371. };
  26372. /**
  26373. * Returns the stride of the VertexBuffer (integer).
  26374. */
  26375. VertexBuffer.prototype.getStrideSize = function () {
  26376. return this._stride;
  26377. };
  26378. /**
  26379. * Returns the offset (integer).
  26380. */
  26381. VertexBuffer.prototype.getOffset = function () {
  26382. return this._offset;
  26383. };
  26384. /**
  26385. * Returns the VertexBuffer total size (integer).
  26386. */
  26387. VertexBuffer.prototype.getSize = function () {
  26388. return this._size;
  26389. };
  26390. /**
  26391. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26392. */
  26393. VertexBuffer.prototype.getIsInstanced = function () {
  26394. return this._instanced;
  26395. };
  26396. /**
  26397. * Returns the instancing divisor, zero for non-instanced (integer).
  26398. */
  26399. VertexBuffer.prototype.getInstanceDivisor = function () {
  26400. return this._instanceDivisor;
  26401. };
  26402. // Methods
  26403. /**
  26404. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26405. * Returns the created WebGLBuffer.
  26406. */
  26407. VertexBuffer.prototype.create = function (data) {
  26408. return this._buffer.create(data);
  26409. };
  26410. /**
  26411. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26412. * This function will create a new buffer if the current one is not updatable
  26413. * Returns the updated WebGLBuffer.
  26414. */
  26415. VertexBuffer.prototype.update = function (data) {
  26416. return this._buffer.update(data);
  26417. };
  26418. /**
  26419. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26420. * Returns the directly updated WebGLBuffer.
  26421. */
  26422. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26423. return this._buffer.updateDirectly(data, offset);
  26424. };
  26425. /**
  26426. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26427. */
  26428. VertexBuffer.prototype.dispose = function () {
  26429. if (this._ownsBuffer) {
  26430. this._buffer.dispose();
  26431. }
  26432. };
  26433. Object.defineProperty(VertexBuffer, "PositionKind", {
  26434. get: function () {
  26435. return VertexBuffer._PositionKind;
  26436. },
  26437. enumerable: true,
  26438. configurable: true
  26439. });
  26440. Object.defineProperty(VertexBuffer, "NormalKind", {
  26441. get: function () {
  26442. return VertexBuffer._NormalKind;
  26443. },
  26444. enumerable: true,
  26445. configurable: true
  26446. });
  26447. Object.defineProperty(VertexBuffer, "TangentKind", {
  26448. get: function () {
  26449. return VertexBuffer._TangentKind;
  26450. },
  26451. enumerable: true,
  26452. configurable: true
  26453. });
  26454. Object.defineProperty(VertexBuffer, "UVKind", {
  26455. get: function () {
  26456. return VertexBuffer._UVKind;
  26457. },
  26458. enumerable: true,
  26459. configurable: true
  26460. });
  26461. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26462. get: function () {
  26463. return VertexBuffer._UV2Kind;
  26464. },
  26465. enumerable: true,
  26466. configurable: true
  26467. });
  26468. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26469. get: function () {
  26470. return VertexBuffer._UV3Kind;
  26471. },
  26472. enumerable: true,
  26473. configurable: true
  26474. });
  26475. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26476. get: function () {
  26477. return VertexBuffer._UV4Kind;
  26478. },
  26479. enumerable: true,
  26480. configurable: true
  26481. });
  26482. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26483. get: function () {
  26484. return VertexBuffer._UV5Kind;
  26485. },
  26486. enumerable: true,
  26487. configurable: true
  26488. });
  26489. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26490. get: function () {
  26491. return VertexBuffer._UV6Kind;
  26492. },
  26493. enumerable: true,
  26494. configurable: true
  26495. });
  26496. Object.defineProperty(VertexBuffer, "ColorKind", {
  26497. get: function () {
  26498. return VertexBuffer._ColorKind;
  26499. },
  26500. enumerable: true,
  26501. configurable: true
  26502. });
  26503. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26504. get: function () {
  26505. return VertexBuffer._MatricesIndicesKind;
  26506. },
  26507. enumerable: true,
  26508. configurable: true
  26509. });
  26510. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26511. get: function () {
  26512. return VertexBuffer._MatricesWeightsKind;
  26513. },
  26514. enumerable: true,
  26515. configurable: true
  26516. });
  26517. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26518. get: function () {
  26519. return VertexBuffer._MatricesIndicesExtraKind;
  26520. },
  26521. enumerable: true,
  26522. configurable: true
  26523. });
  26524. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26525. get: function () {
  26526. return VertexBuffer._MatricesWeightsExtraKind;
  26527. },
  26528. enumerable: true,
  26529. configurable: true
  26530. });
  26531. /**
  26532. * Deduces the stride given a kind.
  26533. * @param kind The kind string to deduce
  26534. * @returns The deduced stride
  26535. */
  26536. VertexBuffer.DeduceStride = function (kind) {
  26537. switch (kind) {
  26538. case VertexBuffer.UVKind:
  26539. case VertexBuffer.UV2Kind:
  26540. case VertexBuffer.UV3Kind:
  26541. case VertexBuffer.UV4Kind:
  26542. case VertexBuffer.UV5Kind:
  26543. case VertexBuffer.UV6Kind:
  26544. return 2;
  26545. case VertexBuffer.NormalKind:
  26546. case VertexBuffer.PositionKind:
  26547. return 3;
  26548. case VertexBuffer.ColorKind:
  26549. case VertexBuffer.MatricesIndicesKind:
  26550. case VertexBuffer.MatricesIndicesExtraKind:
  26551. case VertexBuffer.MatricesWeightsKind:
  26552. case VertexBuffer.MatricesWeightsExtraKind:
  26553. case VertexBuffer.TangentKind:
  26554. return 4;
  26555. default:
  26556. throw new Error("Invalid kind '" + kind + "'");
  26557. }
  26558. };
  26559. // Enums
  26560. VertexBuffer._PositionKind = "position";
  26561. VertexBuffer._NormalKind = "normal";
  26562. VertexBuffer._TangentKind = "tangent";
  26563. VertexBuffer._UVKind = "uv";
  26564. VertexBuffer._UV2Kind = "uv2";
  26565. VertexBuffer._UV3Kind = "uv3";
  26566. VertexBuffer._UV4Kind = "uv4";
  26567. VertexBuffer._UV5Kind = "uv5";
  26568. VertexBuffer._UV6Kind = "uv6";
  26569. VertexBuffer._ColorKind = "color";
  26570. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26571. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26572. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26573. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26574. return VertexBuffer;
  26575. }());
  26576. BABYLON.VertexBuffer = VertexBuffer;
  26577. })(BABYLON || (BABYLON = {}));
  26578. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26579. "use strict";
  26580. var BABYLON;
  26581. (function (BABYLON) {
  26582. /**
  26583. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26584. */
  26585. var DummyInternalTextureTracker = /** @class */ (function () {
  26586. function DummyInternalTextureTracker() {
  26587. /**
  26588. * Gets or set the previous tracker in the list
  26589. */
  26590. this.previous = null;
  26591. /**
  26592. * Gets or set the next tracker in the list
  26593. */
  26594. this.next = null;
  26595. }
  26596. return DummyInternalTextureTracker;
  26597. }());
  26598. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26599. })(BABYLON || (BABYLON = {}));
  26600. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26601. "use strict";
  26602. var BABYLON;
  26603. (function (BABYLON) {
  26604. /**
  26605. * Class used to store data associated with WebGL texture data for the engine
  26606. * This class should not be used directly
  26607. */
  26608. var InternalTexture = /** @class */ (function () {
  26609. /**
  26610. * Creates a new InternalTexture
  26611. * @param engine defines the engine to use
  26612. * @param dataSource defines the type of data that will be used
  26613. */
  26614. function InternalTexture(engine, dataSource) {
  26615. /**
  26616. * Observable called when the texture is loaded
  26617. */
  26618. this.onLoadedObservable = new BABYLON.Observable();
  26619. /**
  26620. * Gets or set the previous tracker in the list
  26621. */
  26622. this.previous = null;
  26623. /**
  26624. * Gets or set the next tracker in the list
  26625. */
  26626. this.next = null;
  26627. // Private
  26628. /** @ignore */
  26629. this._initialSlot = -1;
  26630. /** @ignore */
  26631. this._designatedSlot = -1;
  26632. /** @ignore */
  26633. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26634. /** @ignore */
  26635. this._comparisonFunction = 0;
  26636. /** @ignore */
  26637. this._references = 1;
  26638. this._engine = engine;
  26639. this._dataSource = dataSource;
  26640. this._webGLTexture = engine._createTexture();
  26641. }
  26642. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26643. /**
  26644. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26645. */
  26646. get: function () {
  26647. return this._dataSource;
  26648. },
  26649. enumerable: true,
  26650. configurable: true
  26651. });
  26652. /**
  26653. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26654. */
  26655. InternalTexture.prototype.incrementReferences = function () {
  26656. this._references++;
  26657. };
  26658. /**
  26659. * Change the size of the texture (not the size of the content)
  26660. * @param width defines the new width
  26661. * @param height defines the new height
  26662. * @param depth defines the new depth (1 by default)
  26663. */
  26664. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26665. if (depth === void 0) { depth = 1; }
  26666. this.width = width;
  26667. this.height = height;
  26668. this.depth = depth;
  26669. this.baseWidth = width;
  26670. this.baseHeight = height;
  26671. this.baseDepth = depth;
  26672. this._size = width * height * depth;
  26673. };
  26674. /** @ignore */
  26675. InternalTexture.prototype._rebuild = function () {
  26676. var _this = this;
  26677. var proxy;
  26678. this.isReady = false;
  26679. this._cachedCoordinatesMode = null;
  26680. this._cachedWrapU = null;
  26681. this._cachedWrapV = null;
  26682. this._cachedAnisotropicFilteringLevel = null;
  26683. switch (this._dataSource) {
  26684. case InternalTexture.DATASOURCE_TEMP:
  26685. return;
  26686. case InternalTexture.DATASOURCE_URL:
  26687. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26688. _this.isReady = true;
  26689. }, null, this._buffer, undefined, this.format);
  26690. proxy._swapAndDie(this);
  26691. return;
  26692. case InternalTexture.DATASOURCE_RAW:
  26693. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26694. proxy._swapAndDie(this);
  26695. this.isReady = true;
  26696. return;
  26697. case InternalTexture.DATASOURCE_RAW3D:
  26698. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26699. proxy._swapAndDie(this);
  26700. this.isReady = true;
  26701. return;
  26702. case InternalTexture.DATASOURCE_DYNAMIC:
  26703. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26704. proxy._swapAndDie(this);
  26705. // The engine will make sure to update content so no need to flag it as isReady = true
  26706. return;
  26707. case InternalTexture.DATASOURCE_RENDERTARGET:
  26708. var options = new BABYLON.RenderTargetCreationOptions();
  26709. options.generateDepthBuffer = this._generateDepthBuffer;
  26710. options.generateMipMaps = this.generateMipMaps;
  26711. options.generateStencilBuffer = this._generateStencilBuffer;
  26712. options.samplingMode = this.samplingMode;
  26713. options.type = this.type;
  26714. if (this.isCube) {
  26715. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26716. }
  26717. else {
  26718. var size = {
  26719. width: this.width,
  26720. height: this.height
  26721. };
  26722. proxy = this._engine.createRenderTargetTexture(size, options);
  26723. }
  26724. proxy._swapAndDie(this);
  26725. this.isReady = true;
  26726. return;
  26727. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26728. var depthTextureOptions = {
  26729. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26730. comparisonFunction: this._comparisonFunction,
  26731. generateStencil: this._generateStencilBuffer,
  26732. isCube: this.isCube
  26733. };
  26734. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26735. proxy._swapAndDie(this);
  26736. this.isReady = true;
  26737. return;
  26738. case InternalTexture.DATASOURCE_CUBE:
  26739. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26740. _this.isReady = true;
  26741. }, null, this.format, this._extension);
  26742. proxy._swapAndDie(this);
  26743. return;
  26744. case InternalTexture.DATASOURCE_CUBERAW:
  26745. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26746. proxy._swapAndDie(this);
  26747. this.isReady = true;
  26748. return;
  26749. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26750. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26751. if (proxy) {
  26752. proxy._swapAndDie(_this);
  26753. }
  26754. _this.isReady = true;
  26755. }, null, this.format, this._extension);
  26756. return;
  26757. }
  26758. };
  26759. InternalTexture.prototype._swapAndDie = function (target) {
  26760. target._webGLTexture = this._webGLTexture;
  26761. if (this._framebuffer) {
  26762. target._framebuffer = this._framebuffer;
  26763. }
  26764. if (this._depthStencilBuffer) {
  26765. target._depthStencilBuffer = this._depthStencilBuffer;
  26766. }
  26767. if (this._lodTextureHigh) {
  26768. if (target._lodTextureHigh) {
  26769. target._lodTextureHigh.dispose();
  26770. }
  26771. target._lodTextureHigh = this._lodTextureHigh;
  26772. }
  26773. if (this._lodTextureMid) {
  26774. if (target._lodTextureMid) {
  26775. target._lodTextureMid.dispose();
  26776. }
  26777. target._lodTextureMid = this._lodTextureMid;
  26778. }
  26779. if (this._lodTextureLow) {
  26780. if (target._lodTextureLow) {
  26781. target._lodTextureLow.dispose();
  26782. }
  26783. target._lodTextureLow = this._lodTextureLow;
  26784. }
  26785. var cache = this._engine.getLoadedTexturesCache();
  26786. var index = cache.indexOf(this);
  26787. if (index !== -1) {
  26788. cache.splice(index, 1);
  26789. }
  26790. };
  26791. /**
  26792. * Dispose the current allocated resources
  26793. */
  26794. InternalTexture.prototype.dispose = function () {
  26795. if (!this._webGLTexture) {
  26796. return;
  26797. }
  26798. this._references--;
  26799. if (this._references === 0) {
  26800. this._engine._releaseTexture(this);
  26801. this._webGLTexture = null;
  26802. this.previous = null;
  26803. this.next = null;
  26804. }
  26805. };
  26806. /**
  26807. * The source of the texture data is unknown
  26808. */
  26809. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26810. /**
  26811. * Texture data comes from an URL
  26812. */
  26813. InternalTexture.DATASOURCE_URL = 1;
  26814. /**
  26815. * Texture data is only used for temporary storage
  26816. */
  26817. InternalTexture.DATASOURCE_TEMP = 2;
  26818. /**
  26819. * Texture data comes from raw data (ArrayBuffer)
  26820. */
  26821. InternalTexture.DATASOURCE_RAW = 3;
  26822. /**
  26823. * Texture content is dynamic (video or dynamic texture)
  26824. */
  26825. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26826. /**
  26827. * Texture content is generated by rendering to it
  26828. */
  26829. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26830. /**
  26831. * Texture content is part of a multi render target process
  26832. */
  26833. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26834. /**
  26835. * Texture data comes from a cube data file
  26836. */
  26837. InternalTexture.DATASOURCE_CUBE = 7;
  26838. /**
  26839. * Texture data comes from a raw cube data
  26840. */
  26841. InternalTexture.DATASOURCE_CUBERAW = 8;
  26842. /**
  26843. * Texture data come from a prefiltered cube data file
  26844. */
  26845. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26846. /**
  26847. * Texture content is raw 3D data
  26848. */
  26849. InternalTexture.DATASOURCE_RAW3D = 10;
  26850. /**
  26851. * Texture content is a depth texture
  26852. */
  26853. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26854. return InternalTexture;
  26855. }());
  26856. BABYLON.InternalTexture = InternalTexture;
  26857. })(BABYLON || (BABYLON = {}));
  26858. //# sourceMappingURL=babylon.internalTexture.js.map
  26859. "use strict";
  26860. var BABYLON;
  26861. (function (BABYLON) {
  26862. var BaseTexture = /** @class */ (function () {
  26863. function BaseTexture(scene) {
  26864. this._hasAlpha = false;
  26865. this.getAlphaFromRGB = false;
  26866. this.level = 1;
  26867. this.coordinatesIndex = 0;
  26868. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26869. /**
  26870. * | Value | Type | Description |
  26871. * | ----- | ------------------ | ----------- |
  26872. * | 0 | CLAMP_ADDRESSMODE | |
  26873. * | 1 | WRAP_ADDRESSMODE | |
  26874. * | 2 | MIRROR_ADDRESSMODE | |
  26875. */
  26876. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26877. /**
  26878. * | Value | Type | Description |
  26879. * | ----- | ------------------ | ----------- |
  26880. * | 0 | CLAMP_ADDRESSMODE | |
  26881. * | 1 | WRAP_ADDRESSMODE | |
  26882. * | 2 | MIRROR_ADDRESSMODE | |
  26883. */
  26884. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26885. /**
  26886. * | Value | Type | Description |
  26887. * | ----- | ------------------ | ----------- |
  26888. * | 0 | CLAMP_ADDRESSMODE | |
  26889. * | 1 | WRAP_ADDRESSMODE | |
  26890. * | 2 | MIRROR_ADDRESSMODE | |
  26891. */
  26892. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26893. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26894. this.isCube = false;
  26895. this.is3D = false;
  26896. this.gammaSpace = true;
  26897. this.invertZ = false;
  26898. this.lodLevelInAlpha = false;
  26899. this.lodGenerationOffset = 0.0;
  26900. this.lodGenerationScale = 0.8;
  26901. this.isRenderTarget = false;
  26902. this.animations = new Array();
  26903. /**
  26904. * An event triggered when the texture is disposed.
  26905. * @type {BABYLON.Observable}
  26906. */
  26907. this.onDisposeObservable = new BABYLON.Observable();
  26908. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26909. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26910. if (this._scene) {
  26911. this._scene.textures.push(this);
  26912. }
  26913. this._uid = null;
  26914. }
  26915. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26916. get: function () {
  26917. return this._hasAlpha;
  26918. },
  26919. set: function (value) {
  26920. if (this._hasAlpha === value) {
  26921. return;
  26922. }
  26923. this._hasAlpha = value;
  26924. if (this._scene) {
  26925. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26926. }
  26927. },
  26928. enumerable: true,
  26929. configurable: true
  26930. });
  26931. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26932. get: function () {
  26933. return this._coordinatesMode;
  26934. },
  26935. /**
  26936. * How a texture is mapped.
  26937. *
  26938. * | Value | Type | Description |
  26939. * | ----- | ----------------------------------- | ----------- |
  26940. * | 0 | EXPLICIT_MODE | |
  26941. * | 1 | SPHERICAL_MODE | |
  26942. * | 2 | PLANAR_MODE | |
  26943. * | 3 | CUBIC_MODE | |
  26944. * | 4 | PROJECTION_MODE | |
  26945. * | 5 | SKYBOX_MODE | |
  26946. * | 6 | INVCUBIC_MODE | |
  26947. * | 7 | EQUIRECTANGULAR_MODE | |
  26948. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26949. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26950. */
  26951. set: function (value) {
  26952. if (this._coordinatesMode === value) {
  26953. return;
  26954. }
  26955. this._coordinatesMode = value;
  26956. if (this._scene) {
  26957. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26958. }
  26959. },
  26960. enumerable: true,
  26961. configurable: true
  26962. });
  26963. Object.defineProperty(BaseTexture.prototype, "uid", {
  26964. get: function () {
  26965. if (!this._uid) {
  26966. this._uid = BABYLON.Tools.RandomId();
  26967. }
  26968. return this._uid;
  26969. },
  26970. enumerable: true,
  26971. configurable: true
  26972. });
  26973. BaseTexture.prototype.toString = function () {
  26974. return this.name;
  26975. };
  26976. BaseTexture.prototype.getClassName = function () {
  26977. return "BaseTexture";
  26978. };
  26979. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26980. set: function (callback) {
  26981. if (this._onDisposeObserver) {
  26982. this.onDisposeObservable.remove(this._onDisposeObserver);
  26983. }
  26984. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26985. },
  26986. enumerable: true,
  26987. configurable: true
  26988. });
  26989. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26990. get: function () {
  26991. return true;
  26992. },
  26993. enumerable: true,
  26994. configurable: true
  26995. });
  26996. BaseTexture.prototype.getScene = function () {
  26997. return this._scene;
  26998. };
  26999. BaseTexture.prototype.getTextureMatrix = function () {
  27000. return BABYLON.Matrix.IdentityReadOnly;
  27001. };
  27002. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  27003. return BABYLON.Matrix.IdentityReadOnly;
  27004. };
  27005. BaseTexture.prototype.getInternalTexture = function () {
  27006. return this._texture;
  27007. };
  27008. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  27009. return !this.isBlocking || this.isReady();
  27010. };
  27011. BaseTexture.prototype.isReady = function () {
  27012. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27013. this.delayLoad();
  27014. return false;
  27015. }
  27016. if (this._texture) {
  27017. return this._texture.isReady;
  27018. }
  27019. return false;
  27020. };
  27021. BaseTexture.prototype.getSize = function () {
  27022. if (this._texture && this._texture.width) {
  27023. return new BABYLON.Size(this._texture.width, this._texture.height);
  27024. }
  27025. if (this._texture && this._texture._size) {
  27026. return new BABYLON.Size(this._texture._size, this._texture._size);
  27027. }
  27028. return BABYLON.Size.Zero();
  27029. };
  27030. BaseTexture.prototype.getBaseSize = function () {
  27031. if (!this.isReady() || !this._texture)
  27032. return BABYLON.Size.Zero();
  27033. if (this._texture._size) {
  27034. return new BABYLON.Size(this._texture._size, this._texture._size);
  27035. }
  27036. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  27037. };
  27038. BaseTexture.prototype.scale = function (ratio) {
  27039. };
  27040. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  27041. get: function () {
  27042. return false;
  27043. },
  27044. enumerable: true,
  27045. configurable: true
  27046. });
  27047. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  27048. if (!this._scene) {
  27049. return null;
  27050. }
  27051. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  27052. for (var index = 0; index < texturesCache.length; index++) {
  27053. var texturesCacheEntry = texturesCache[index];
  27054. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  27055. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  27056. texturesCacheEntry.incrementReferences();
  27057. return texturesCacheEntry;
  27058. }
  27059. }
  27060. }
  27061. return null;
  27062. };
  27063. BaseTexture.prototype._rebuild = function () {
  27064. };
  27065. BaseTexture.prototype.delayLoad = function () {
  27066. };
  27067. BaseTexture.prototype.clone = function () {
  27068. return null;
  27069. };
  27070. Object.defineProperty(BaseTexture.prototype, "textureType", {
  27071. get: function () {
  27072. if (!this._texture) {
  27073. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27074. }
  27075. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27076. },
  27077. enumerable: true,
  27078. configurable: true
  27079. });
  27080. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  27081. get: function () {
  27082. if (!this._texture) {
  27083. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27084. }
  27085. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27086. },
  27087. enumerable: true,
  27088. configurable: true
  27089. });
  27090. BaseTexture.prototype.readPixels = function (faceIndex) {
  27091. if (faceIndex === void 0) { faceIndex = 0; }
  27092. if (!this._texture) {
  27093. return null;
  27094. }
  27095. var size = this.getSize();
  27096. var scene = this.getScene();
  27097. if (!scene) {
  27098. return null;
  27099. }
  27100. var engine = scene.getEngine();
  27101. if (this._texture.isCube) {
  27102. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  27103. }
  27104. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  27105. };
  27106. BaseTexture.prototype.releaseInternalTexture = function () {
  27107. if (this._texture) {
  27108. this._texture.dispose();
  27109. this._texture = null;
  27110. }
  27111. };
  27112. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  27113. get: function () {
  27114. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  27115. return null;
  27116. }
  27117. if (!this._texture._sphericalPolynomial) {
  27118. this._texture._sphericalPolynomial =
  27119. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  27120. }
  27121. return this._texture._sphericalPolynomial;
  27122. },
  27123. set: function (value) {
  27124. if (this._texture) {
  27125. this._texture._sphericalPolynomial = value;
  27126. }
  27127. },
  27128. enumerable: true,
  27129. configurable: true
  27130. });
  27131. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  27132. get: function () {
  27133. if (this._texture) {
  27134. return this._texture._lodTextureHigh;
  27135. }
  27136. return null;
  27137. },
  27138. enumerable: true,
  27139. configurable: true
  27140. });
  27141. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  27142. get: function () {
  27143. if (this._texture) {
  27144. return this._texture._lodTextureMid;
  27145. }
  27146. return null;
  27147. },
  27148. enumerable: true,
  27149. configurable: true
  27150. });
  27151. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  27152. get: function () {
  27153. if (this._texture) {
  27154. return this._texture._lodTextureLow;
  27155. }
  27156. return null;
  27157. },
  27158. enumerable: true,
  27159. configurable: true
  27160. });
  27161. BaseTexture.prototype.dispose = function () {
  27162. if (!this._scene) {
  27163. return;
  27164. }
  27165. // Animations
  27166. this._scene.stopAnimation(this);
  27167. // Remove from scene
  27168. this._scene._removePendingData(this);
  27169. var index = this._scene.textures.indexOf(this);
  27170. if (index >= 0) {
  27171. this._scene.textures.splice(index, 1);
  27172. }
  27173. if (this._texture === undefined) {
  27174. return;
  27175. }
  27176. // Release
  27177. this.releaseInternalTexture();
  27178. // Callback
  27179. this.onDisposeObservable.notifyObservers(this);
  27180. this.onDisposeObservable.clear();
  27181. };
  27182. BaseTexture.prototype.serialize = function () {
  27183. if (!this.name) {
  27184. return null;
  27185. }
  27186. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  27187. // Animations
  27188. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27189. return serializationObject;
  27190. };
  27191. BaseTexture.WhenAllReady = function (textures, callback) {
  27192. var numRemaining = textures.length;
  27193. if (numRemaining === 0) {
  27194. callback();
  27195. return;
  27196. }
  27197. var _loop_1 = function () {
  27198. texture = textures[i];
  27199. if (texture.isReady()) {
  27200. if (--numRemaining === 0) {
  27201. callback();
  27202. }
  27203. }
  27204. else {
  27205. onLoadObservable = texture.onLoadObservable;
  27206. var onLoadCallback_1 = function () {
  27207. onLoadObservable.removeCallback(onLoadCallback_1);
  27208. if (--numRemaining === 0) {
  27209. callback();
  27210. }
  27211. };
  27212. onLoadObservable.add(onLoadCallback_1);
  27213. }
  27214. };
  27215. var texture, onLoadObservable;
  27216. for (var i = 0; i < textures.length; i++) {
  27217. _loop_1();
  27218. }
  27219. };
  27220. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  27221. __decorate([
  27222. BABYLON.serialize()
  27223. ], BaseTexture.prototype, "name", void 0);
  27224. __decorate([
  27225. BABYLON.serialize("hasAlpha")
  27226. ], BaseTexture.prototype, "_hasAlpha", void 0);
  27227. __decorate([
  27228. BABYLON.serialize()
  27229. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  27230. __decorate([
  27231. BABYLON.serialize()
  27232. ], BaseTexture.prototype, "level", void 0);
  27233. __decorate([
  27234. BABYLON.serialize()
  27235. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  27236. __decorate([
  27237. BABYLON.serialize("coordinatesMode")
  27238. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  27239. __decorate([
  27240. BABYLON.serialize()
  27241. ], BaseTexture.prototype, "wrapU", void 0);
  27242. __decorate([
  27243. BABYLON.serialize()
  27244. ], BaseTexture.prototype, "wrapV", void 0);
  27245. __decorate([
  27246. BABYLON.serialize()
  27247. ], BaseTexture.prototype, "wrapR", void 0);
  27248. __decorate([
  27249. BABYLON.serialize()
  27250. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27251. __decorate([
  27252. BABYLON.serialize()
  27253. ], BaseTexture.prototype, "isCube", void 0);
  27254. __decorate([
  27255. BABYLON.serialize()
  27256. ], BaseTexture.prototype, "is3D", void 0);
  27257. __decorate([
  27258. BABYLON.serialize()
  27259. ], BaseTexture.prototype, "gammaSpace", void 0);
  27260. __decorate([
  27261. BABYLON.serialize()
  27262. ], BaseTexture.prototype, "invertZ", void 0);
  27263. __decorate([
  27264. BABYLON.serialize()
  27265. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  27266. __decorate([
  27267. BABYLON.serialize()
  27268. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  27269. __decorate([
  27270. BABYLON.serialize()
  27271. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  27272. __decorate([
  27273. BABYLON.serialize()
  27274. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27275. return BaseTexture;
  27276. }());
  27277. BABYLON.BaseTexture = BaseTexture;
  27278. })(BABYLON || (BABYLON = {}));
  27279. //# sourceMappingURL=babylon.baseTexture.js.map
  27280. "use strict";
  27281. var BABYLON;
  27282. (function (BABYLON) {
  27283. var Texture = /** @class */ (function (_super) {
  27284. __extends(Texture, _super);
  27285. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27286. if (noMipmap === void 0) { noMipmap = false; }
  27287. if (invertY === void 0) { invertY = true; }
  27288. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27289. if (onLoad === void 0) { onLoad = null; }
  27290. if (onError === void 0) { onError = null; }
  27291. if (buffer === void 0) { buffer = null; }
  27292. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27293. var _this = _super.call(this, scene) || this;
  27294. _this.uOffset = 0;
  27295. _this.vOffset = 0;
  27296. _this.uScale = 1.0;
  27297. _this.vScale = 1.0;
  27298. _this.uAng = 0;
  27299. _this.vAng = 0;
  27300. _this.wAng = 0;
  27301. _this._isBlocking = true;
  27302. _this.name = url || "";
  27303. _this.url = url;
  27304. _this._noMipmap = noMipmap;
  27305. _this._invertY = invertY;
  27306. _this._samplingMode = samplingMode;
  27307. _this._buffer = buffer;
  27308. _this._deleteBuffer = deleteBuffer;
  27309. if (format) {
  27310. _this._format = format;
  27311. }
  27312. scene = _this.getScene();
  27313. if (!scene) {
  27314. return _this;
  27315. }
  27316. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  27317. var load = function () {
  27318. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  27319. _this.onLoadObservable.notifyObservers(_this);
  27320. }
  27321. if (onLoad) {
  27322. onLoad();
  27323. }
  27324. if (!_this.isBlocking && scene) {
  27325. scene.resetCachedMaterial();
  27326. }
  27327. };
  27328. if (!_this.url) {
  27329. _this._delayedOnLoad = load;
  27330. _this._delayedOnError = onError;
  27331. return _this;
  27332. }
  27333. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  27334. if (!_this._texture) {
  27335. if (!scene.useDelayedTextureLoading) {
  27336. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  27337. if (deleteBuffer) {
  27338. delete _this._buffer;
  27339. }
  27340. }
  27341. else {
  27342. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27343. _this._delayedOnLoad = load;
  27344. _this._delayedOnError = onError;
  27345. }
  27346. }
  27347. else {
  27348. if (_this._texture.isReady) {
  27349. BABYLON.Tools.SetImmediate(function () { return load(); });
  27350. }
  27351. else {
  27352. _this._texture.onLoadedObservable.add(load);
  27353. }
  27354. }
  27355. return _this;
  27356. }
  27357. Object.defineProperty(Texture.prototype, "noMipmap", {
  27358. get: function () {
  27359. return this._noMipmap;
  27360. },
  27361. enumerable: true,
  27362. configurable: true
  27363. });
  27364. Object.defineProperty(Texture.prototype, "isBlocking", {
  27365. get: function () {
  27366. return this._isBlocking;
  27367. },
  27368. set: function (value) {
  27369. this._isBlocking = value;
  27370. },
  27371. enumerable: true,
  27372. configurable: true
  27373. });
  27374. Object.defineProperty(Texture.prototype, "samplingMode", {
  27375. get: function () {
  27376. return this._samplingMode;
  27377. },
  27378. enumerable: true,
  27379. configurable: true
  27380. });
  27381. Texture.prototype.updateURL = function (url) {
  27382. this.url = url;
  27383. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27384. this.delayLoad();
  27385. };
  27386. Texture.prototype.delayLoad = function () {
  27387. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27388. return;
  27389. }
  27390. var scene = this.getScene();
  27391. if (!scene) {
  27392. return;
  27393. }
  27394. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27395. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27396. if (!this._texture) {
  27397. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27398. if (this._deleteBuffer) {
  27399. delete this._buffer;
  27400. }
  27401. }
  27402. else {
  27403. if (this._delayedOnLoad) {
  27404. if (this._texture.isReady) {
  27405. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27406. }
  27407. else {
  27408. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27409. }
  27410. }
  27411. }
  27412. this._delayedOnLoad = null;
  27413. this._delayedOnError = null;
  27414. };
  27415. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27416. if (!this._texture) {
  27417. return;
  27418. }
  27419. var scene = this.getScene();
  27420. if (!scene) {
  27421. return;
  27422. }
  27423. this._samplingMode = samplingMode;
  27424. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27425. };
  27426. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27427. x *= this.uScale;
  27428. y *= this.vScale;
  27429. x -= 0.5 * this.uScale;
  27430. y -= 0.5 * this.vScale;
  27431. z -= 0.5;
  27432. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27433. t.x += 0.5 * this.uScale + this.uOffset;
  27434. t.y += 0.5 * this.vScale + this.vOffset;
  27435. t.z += 0.5;
  27436. };
  27437. Texture.prototype.getTextureMatrix = function () {
  27438. var _this = this;
  27439. if (this.uOffset === this._cachedUOffset &&
  27440. this.vOffset === this._cachedVOffset &&
  27441. this.uScale === this._cachedUScale &&
  27442. this.vScale === this._cachedVScale &&
  27443. this.uAng === this._cachedUAng &&
  27444. this.vAng === this._cachedVAng &&
  27445. this.wAng === this._cachedWAng) {
  27446. return this._cachedTextureMatrix;
  27447. }
  27448. this._cachedUOffset = this.uOffset;
  27449. this._cachedVOffset = this.vOffset;
  27450. this._cachedUScale = this.uScale;
  27451. this._cachedVScale = this.vScale;
  27452. this._cachedUAng = this.uAng;
  27453. this._cachedVAng = this.vAng;
  27454. this._cachedWAng = this.wAng;
  27455. if (!this._cachedTextureMatrix) {
  27456. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27457. this._rowGenerationMatrix = new BABYLON.Matrix();
  27458. this._t0 = BABYLON.Vector3.Zero();
  27459. this._t1 = BABYLON.Vector3.Zero();
  27460. this._t2 = BABYLON.Vector3.Zero();
  27461. }
  27462. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27463. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27464. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27465. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27466. this._t1.subtractInPlace(this._t0);
  27467. this._t2.subtractInPlace(this._t0);
  27468. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27469. this._cachedTextureMatrix.m[0] = this._t1.x;
  27470. this._cachedTextureMatrix.m[1] = this._t1.y;
  27471. this._cachedTextureMatrix.m[2] = this._t1.z;
  27472. this._cachedTextureMatrix.m[4] = this._t2.x;
  27473. this._cachedTextureMatrix.m[5] = this._t2.y;
  27474. this._cachedTextureMatrix.m[6] = this._t2.z;
  27475. this._cachedTextureMatrix.m[8] = this._t0.x;
  27476. this._cachedTextureMatrix.m[9] = this._t0.y;
  27477. this._cachedTextureMatrix.m[10] = this._t0.z;
  27478. var scene = this.getScene();
  27479. if (!scene) {
  27480. return this._cachedTextureMatrix;
  27481. }
  27482. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27483. return mat.hasTexture(_this);
  27484. });
  27485. return this._cachedTextureMatrix;
  27486. };
  27487. Texture.prototype.getReflectionTextureMatrix = function () {
  27488. var _this = this;
  27489. var scene = this.getScene();
  27490. if (!scene) {
  27491. return this._cachedTextureMatrix;
  27492. }
  27493. if (this.uOffset === this._cachedUOffset &&
  27494. this.vOffset === this._cachedVOffset &&
  27495. this.uScale === this._cachedUScale &&
  27496. this.vScale === this._cachedVScale &&
  27497. this.coordinatesMode === this._cachedCoordinatesMode) {
  27498. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27499. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27500. return this._cachedTextureMatrix;
  27501. }
  27502. }
  27503. else {
  27504. return this._cachedTextureMatrix;
  27505. }
  27506. }
  27507. if (!this._cachedTextureMatrix) {
  27508. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27509. }
  27510. if (!this._projectionModeMatrix) {
  27511. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27512. }
  27513. this._cachedUOffset = this.uOffset;
  27514. this._cachedVOffset = this.vOffset;
  27515. this._cachedUScale = this.uScale;
  27516. this._cachedVScale = this.vScale;
  27517. this._cachedCoordinatesMode = this.coordinatesMode;
  27518. switch (this.coordinatesMode) {
  27519. case Texture.PLANAR_MODE:
  27520. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27521. this._cachedTextureMatrix[0] = this.uScale;
  27522. this._cachedTextureMatrix[5] = this.vScale;
  27523. this._cachedTextureMatrix[12] = this.uOffset;
  27524. this._cachedTextureMatrix[13] = this.vOffset;
  27525. break;
  27526. case Texture.PROJECTION_MODE:
  27527. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27528. this._projectionModeMatrix.m[0] = 0.5;
  27529. this._projectionModeMatrix.m[5] = -0.5;
  27530. this._projectionModeMatrix.m[10] = 0.0;
  27531. this._projectionModeMatrix.m[12] = 0.5;
  27532. this._projectionModeMatrix.m[13] = 0.5;
  27533. this._projectionModeMatrix.m[14] = 1.0;
  27534. this._projectionModeMatrix.m[15] = 1.0;
  27535. var projectionMatrix = scene.getProjectionMatrix();
  27536. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27537. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27538. break;
  27539. default:
  27540. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27541. break;
  27542. }
  27543. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27544. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27545. });
  27546. return this._cachedTextureMatrix;
  27547. };
  27548. Texture.prototype.clone = function () {
  27549. var _this = this;
  27550. return BABYLON.SerializationHelper.Clone(function () {
  27551. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27552. }, this);
  27553. };
  27554. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27555. get: function () {
  27556. if (!this._onLoadObservable) {
  27557. this._onLoadObservable = new BABYLON.Observable();
  27558. }
  27559. return this._onLoadObservable;
  27560. },
  27561. enumerable: true,
  27562. configurable: true
  27563. });
  27564. Texture.prototype.serialize = function () {
  27565. var serializationObject = _super.prototype.serialize.call(this);
  27566. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27567. serializationObject.base64String = this._buffer;
  27568. serializationObject.name = serializationObject.name.replace("data:", "");
  27569. }
  27570. return serializationObject;
  27571. };
  27572. Texture.prototype.getClassName = function () {
  27573. return "Texture";
  27574. };
  27575. Texture.prototype.dispose = function () {
  27576. _super.prototype.dispose.call(this);
  27577. if (this.onLoadObservable) {
  27578. this.onLoadObservable.clear();
  27579. this._onLoadObservable = null;
  27580. }
  27581. this._delayedOnLoad = null;
  27582. this._delayedOnError = null;
  27583. };
  27584. // Statics
  27585. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27586. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27587. if (onLoad === void 0) { onLoad = null; }
  27588. if (onError === void 0) { onError = null; }
  27589. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27590. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27591. };
  27592. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27593. if (parsedTexture.customType) {
  27594. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27595. // Update Sampling Mode
  27596. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27597. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27598. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27599. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27600. }
  27601. }
  27602. return parsedCustomTexture;
  27603. }
  27604. if (parsedTexture.isCube) {
  27605. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27606. }
  27607. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27608. return null;
  27609. }
  27610. var texture = BABYLON.SerializationHelper.Parse(function () {
  27611. var generateMipMaps = true;
  27612. if (parsedTexture.noMipmap) {
  27613. generateMipMaps = false;
  27614. }
  27615. if (parsedTexture.mirrorPlane) {
  27616. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27617. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27618. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27619. return mirrorTexture;
  27620. }
  27621. else if (parsedTexture.isRenderTarget) {
  27622. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27623. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27624. return renderTargetTexture;
  27625. }
  27626. else {
  27627. var texture;
  27628. if (parsedTexture.base64String) {
  27629. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27630. }
  27631. else {
  27632. var url = rootUrl + parsedTexture.name;
  27633. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27634. url = parsedTexture.url;
  27635. }
  27636. texture = new Texture(url, scene, !generateMipMaps);
  27637. }
  27638. return texture;
  27639. }
  27640. }, parsedTexture, scene);
  27641. // Update Sampling Mode
  27642. if (parsedTexture.samplingMode) {
  27643. var sampling = parsedTexture.samplingMode;
  27644. if (texture._samplingMode !== sampling) {
  27645. texture.updateSamplingMode(sampling);
  27646. }
  27647. }
  27648. // Animations
  27649. if (parsedTexture.animations) {
  27650. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27651. var parsedAnimation = parsedTexture.animations[animationIndex];
  27652. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27653. }
  27654. }
  27655. return texture;
  27656. };
  27657. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27658. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27659. if (noMipmap === void 0) { noMipmap = false; }
  27660. if (invertY === void 0) { invertY = true; }
  27661. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27662. if (onLoad === void 0) { onLoad = null; }
  27663. if (onError === void 0) { onError = null; }
  27664. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27665. if (name.substr(0, 5) !== "data:") {
  27666. name = "data:" + name;
  27667. }
  27668. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27669. };
  27670. // Constants
  27671. Texture.NEAREST_SAMPLINGMODE = 1;
  27672. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27673. Texture.BILINEAR_SAMPLINGMODE = 2;
  27674. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27675. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27676. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27677. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27678. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27679. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27680. Texture.NEAREST_LINEAR = 7;
  27681. Texture.NEAREST_NEAREST = 8;
  27682. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27683. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27684. Texture.LINEAR_LINEAR = 11;
  27685. Texture.LINEAR_NEAREST = 12;
  27686. Texture.EXPLICIT_MODE = 0;
  27687. Texture.SPHERICAL_MODE = 1;
  27688. Texture.PLANAR_MODE = 2;
  27689. Texture.CUBIC_MODE = 3;
  27690. Texture.PROJECTION_MODE = 4;
  27691. Texture.SKYBOX_MODE = 5;
  27692. Texture.INVCUBIC_MODE = 6;
  27693. Texture.EQUIRECTANGULAR_MODE = 7;
  27694. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27695. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27696. Texture.CLAMP_ADDRESSMODE = 0;
  27697. Texture.WRAP_ADDRESSMODE = 1;
  27698. Texture.MIRROR_ADDRESSMODE = 2;
  27699. /**
  27700. * 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
  27701. */
  27702. Texture.UseSerializedUrlIfAny = false;
  27703. __decorate([
  27704. BABYLON.serialize()
  27705. ], Texture.prototype, "url", void 0);
  27706. __decorate([
  27707. BABYLON.serialize()
  27708. ], Texture.prototype, "uOffset", void 0);
  27709. __decorate([
  27710. BABYLON.serialize()
  27711. ], Texture.prototype, "vOffset", void 0);
  27712. __decorate([
  27713. BABYLON.serialize()
  27714. ], Texture.prototype, "uScale", void 0);
  27715. __decorate([
  27716. BABYLON.serialize()
  27717. ], Texture.prototype, "vScale", void 0);
  27718. __decorate([
  27719. BABYLON.serialize()
  27720. ], Texture.prototype, "uAng", void 0);
  27721. __decorate([
  27722. BABYLON.serialize()
  27723. ], Texture.prototype, "vAng", void 0);
  27724. __decorate([
  27725. BABYLON.serialize()
  27726. ], Texture.prototype, "wAng", void 0);
  27727. __decorate([
  27728. BABYLON.serialize()
  27729. ], Texture.prototype, "isBlocking", null);
  27730. return Texture;
  27731. }(BABYLON.BaseTexture));
  27732. BABYLON.Texture = Texture;
  27733. })(BABYLON || (BABYLON = {}));
  27734. //# sourceMappingURL=babylon.texture.js.map
  27735. "use strict";
  27736. var BABYLON;
  27737. (function (BABYLON) {
  27738. var _InstancesBatch = /** @class */ (function () {
  27739. function _InstancesBatch() {
  27740. this.mustReturn = false;
  27741. this.visibleInstances = new Array();
  27742. this.renderSelf = new Array();
  27743. }
  27744. return _InstancesBatch;
  27745. }());
  27746. BABYLON._InstancesBatch = _InstancesBatch;
  27747. var Mesh = /** @class */ (function (_super) {
  27748. __extends(Mesh, _super);
  27749. /**
  27750. * @constructor
  27751. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27752. * @param {Scene} scene The scene to add this mesh to.
  27753. * @param {Node} parent The parent of this mesh, if it has one
  27754. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27755. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27756. * When false, achieved by calling a clone(), also passing False.
  27757. * This will make creation of children, recursive.
  27758. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27759. */
  27760. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27761. if (scene === void 0) { scene = null; }
  27762. if (parent === void 0) { parent = null; }
  27763. if (source === void 0) { source = null; }
  27764. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27765. var _this = _super.call(this, name, scene) || this;
  27766. // Events
  27767. /**
  27768. * An event triggered before rendering the mesh
  27769. * @type {BABYLON.Observable}
  27770. */
  27771. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27772. /**
  27773. * An event triggered after rendering the mesh
  27774. * @type {BABYLON.Observable}
  27775. */
  27776. _this.onAfterRenderObservable = new BABYLON.Observable();
  27777. /**
  27778. * An event triggered before drawing the mesh
  27779. * @type {BABYLON.Observable}
  27780. */
  27781. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27782. // Members
  27783. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27784. _this.instances = new Array();
  27785. _this._LODLevels = new Array();
  27786. _this._visibleInstances = {};
  27787. _this._renderIdForInstances = new Array();
  27788. _this._batchCache = new _InstancesBatch();
  27789. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27790. // Use by builder only to know what orientation were the mesh build in.
  27791. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27792. _this.overrideMaterialSideOrientation = null;
  27793. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27794. // Will be used to save a source mesh reference, If any
  27795. _this._source = null;
  27796. scene = _this.getScene();
  27797. if (source) {
  27798. // Source mesh
  27799. _this._source = source;
  27800. // Geometry
  27801. if (source._geometry) {
  27802. source._geometry.applyToMesh(_this);
  27803. }
  27804. // Deep copy
  27805. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27806. // Metadata
  27807. if (source.metadata && source.metadata.clone) {
  27808. _this.metadata = source.metadata.clone();
  27809. }
  27810. else {
  27811. _this.metadata = source.metadata;
  27812. }
  27813. // Tags
  27814. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27815. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27816. }
  27817. // Parent
  27818. _this.parent = source.parent;
  27819. // Pivot
  27820. _this.setPivotMatrix(source.getPivotMatrix());
  27821. _this.id = name + "." + source.id;
  27822. // Material
  27823. _this.material = source.material;
  27824. var index;
  27825. if (!doNotCloneChildren) {
  27826. // Children
  27827. var directDescendants = source.getDescendants(true);
  27828. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27829. var child = directDescendants[index_1];
  27830. if (child.clone) {
  27831. child.clone(name + "." + child.name, _this);
  27832. }
  27833. }
  27834. }
  27835. // Physics clone
  27836. var physicsEngine = _this.getScene().getPhysicsEngine();
  27837. if (clonePhysicsImpostor && physicsEngine) {
  27838. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27839. if (impostor) {
  27840. _this.physicsImpostor = impostor.clone(_this);
  27841. }
  27842. }
  27843. // Particles
  27844. for (index = 0; index < scene.particleSystems.length; index++) {
  27845. var system = scene.particleSystems[index];
  27846. if (system.emitter === source) {
  27847. system.clone(system.name, _this);
  27848. }
  27849. }
  27850. _this.computeWorldMatrix(true);
  27851. }
  27852. // Parent
  27853. if (parent !== null) {
  27854. _this.parent = parent;
  27855. }
  27856. return _this;
  27857. }
  27858. Object.defineProperty(Mesh, "FRONTSIDE", {
  27859. /**
  27860. * Mesh side orientation : usually the external or front surface
  27861. */
  27862. get: function () {
  27863. return Mesh._FRONTSIDE;
  27864. },
  27865. enumerable: true,
  27866. configurable: true
  27867. });
  27868. Object.defineProperty(Mesh, "BACKSIDE", {
  27869. /**
  27870. * Mesh side orientation : usually the internal or back surface
  27871. */
  27872. get: function () {
  27873. return Mesh._BACKSIDE;
  27874. },
  27875. enumerable: true,
  27876. configurable: true
  27877. });
  27878. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27879. /**
  27880. * Mesh side orientation : both internal and external or front and back surfaces
  27881. */
  27882. get: function () {
  27883. return Mesh._DOUBLESIDE;
  27884. },
  27885. enumerable: true,
  27886. configurable: true
  27887. });
  27888. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27889. /**
  27890. * Mesh side orientation : by default, `FRONTSIDE`
  27891. */
  27892. get: function () {
  27893. return Mesh._DEFAULTSIDE;
  27894. },
  27895. enumerable: true,
  27896. configurable: true
  27897. });
  27898. Object.defineProperty(Mesh, "NO_CAP", {
  27899. /**
  27900. * Mesh cap setting : no cap
  27901. */
  27902. get: function () {
  27903. return Mesh._NO_CAP;
  27904. },
  27905. enumerable: true,
  27906. configurable: true
  27907. });
  27908. Object.defineProperty(Mesh, "CAP_START", {
  27909. /**
  27910. * Mesh cap setting : one cap at the beginning of the mesh
  27911. */
  27912. get: function () {
  27913. return Mesh._CAP_START;
  27914. },
  27915. enumerable: true,
  27916. configurable: true
  27917. });
  27918. Object.defineProperty(Mesh, "CAP_END", {
  27919. /**
  27920. * Mesh cap setting : one cap at the end of the mesh
  27921. */
  27922. get: function () {
  27923. return Mesh._CAP_END;
  27924. },
  27925. enumerable: true,
  27926. configurable: true
  27927. });
  27928. Object.defineProperty(Mesh, "CAP_ALL", {
  27929. /**
  27930. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27931. */
  27932. get: function () {
  27933. return Mesh._CAP_ALL;
  27934. },
  27935. enumerable: true,
  27936. configurable: true
  27937. });
  27938. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27939. set: function (callback) {
  27940. if (this._onBeforeDrawObserver) {
  27941. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27942. }
  27943. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27944. },
  27945. enumerable: true,
  27946. configurable: true
  27947. });
  27948. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27949. get: function () {
  27950. return this._morphTargetManager;
  27951. },
  27952. set: function (value) {
  27953. if (this._morphTargetManager === value) {
  27954. return;
  27955. }
  27956. this._morphTargetManager = value;
  27957. this._syncGeometryWithMorphTargetManager();
  27958. },
  27959. enumerable: true,
  27960. configurable: true
  27961. });
  27962. Object.defineProperty(Mesh.prototype, "source", {
  27963. get: function () {
  27964. return this._source;
  27965. },
  27966. enumerable: true,
  27967. configurable: true
  27968. });
  27969. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27970. get: function () {
  27971. return this._unIndexed;
  27972. },
  27973. set: function (value) {
  27974. if (this._unIndexed !== value) {
  27975. this._unIndexed = value;
  27976. this._markSubMeshesAsAttributesDirty();
  27977. }
  27978. },
  27979. enumerable: true,
  27980. configurable: true
  27981. });
  27982. // Methods
  27983. /**
  27984. * Returns the string "Mesh".
  27985. */
  27986. Mesh.prototype.getClassName = function () {
  27987. return "Mesh";
  27988. };
  27989. /**
  27990. * Returns a string.
  27991. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27992. */
  27993. Mesh.prototype.toString = function (fullDetails) {
  27994. var ret = _super.prototype.toString.call(this, fullDetails);
  27995. ret += ", n vertices: " + this.getTotalVertices();
  27996. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27997. if (this.animations) {
  27998. for (var i = 0; i < this.animations.length; i++) {
  27999. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  28000. }
  28001. }
  28002. if (fullDetails) {
  28003. if (this._geometry) {
  28004. var ib = this.getIndices();
  28005. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28006. if (vb && ib) {
  28007. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  28008. }
  28009. }
  28010. else {
  28011. ret += ", flat shading: UNKNOWN";
  28012. }
  28013. }
  28014. return ret;
  28015. };
  28016. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  28017. /**
  28018. * True if the mesh has some Levels Of Details (LOD).
  28019. * Returns a boolean.
  28020. */
  28021. get: function () {
  28022. return this._LODLevels.length > 0;
  28023. },
  28024. enumerable: true,
  28025. configurable: true
  28026. });
  28027. /**
  28028. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  28029. * @returns an array of {BABYLON.MeshLODLevel}
  28030. */
  28031. Mesh.prototype.getLODLevels = function () {
  28032. return this._LODLevels;
  28033. };
  28034. Mesh.prototype._sortLODLevels = function () {
  28035. this._LODLevels.sort(function (a, b) {
  28036. if (a.distance < b.distance) {
  28037. return 1;
  28038. }
  28039. if (a.distance > b.distance) {
  28040. return -1;
  28041. }
  28042. return 0;
  28043. });
  28044. };
  28045. /**
  28046. * Add a mesh as LOD level triggered at the given distance.
  28047. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28048. * @param {number} distance The distance from the center of the object to show this level
  28049. * @param {Mesh} mesh The mesh to be added as LOD level
  28050. * @return {Mesh} This mesh (for chaining)
  28051. */
  28052. Mesh.prototype.addLODLevel = function (distance, mesh) {
  28053. if (mesh && mesh._masterMesh) {
  28054. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  28055. return this;
  28056. }
  28057. var level = new BABYLON.MeshLODLevel(distance, mesh);
  28058. this._LODLevels.push(level);
  28059. if (mesh) {
  28060. mesh._masterMesh = this;
  28061. }
  28062. this._sortLODLevels();
  28063. return this;
  28064. };
  28065. /**
  28066. * Returns the LOD level mesh at the passed distance or null if not found.
  28067. * It is related to the method `addLODLevel(distance, mesh)`.
  28068. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28069. * Returns an object Mesh or `null`.
  28070. */
  28071. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  28072. for (var index = 0; index < this._LODLevels.length; index++) {
  28073. var level = this._LODLevels[index];
  28074. if (level.distance === distance) {
  28075. return level.mesh;
  28076. }
  28077. }
  28078. return null;
  28079. };
  28080. /**
  28081. * Remove a mesh from the LOD array
  28082. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28083. * @param {Mesh} mesh The mesh to be removed.
  28084. * @return {Mesh} This mesh (for chaining)
  28085. */
  28086. Mesh.prototype.removeLODLevel = function (mesh) {
  28087. for (var index = 0; index < this._LODLevels.length; index++) {
  28088. if (this._LODLevels[index].mesh === mesh) {
  28089. this._LODLevels.splice(index, 1);
  28090. if (mesh) {
  28091. mesh._masterMesh = null;
  28092. }
  28093. }
  28094. }
  28095. this._sortLODLevels();
  28096. return this;
  28097. };
  28098. /**
  28099. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  28100. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28101. */
  28102. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  28103. if (!this._LODLevels || this._LODLevels.length === 0) {
  28104. return this;
  28105. }
  28106. var bSphere;
  28107. if (boundingSphere) {
  28108. bSphere = boundingSphere;
  28109. }
  28110. else {
  28111. var boundingInfo = this.getBoundingInfo();
  28112. bSphere = boundingInfo.boundingSphere;
  28113. }
  28114. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  28115. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  28116. if (this.onLODLevelSelection) {
  28117. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  28118. }
  28119. return this;
  28120. }
  28121. for (var index = 0; index < this._LODLevels.length; index++) {
  28122. var level = this._LODLevels[index];
  28123. if (level.distance < distanceToCamera) {
  28124. if (level.mesh) {
  28125. level.mesh._preActivate();
  28126. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  28127. }
  28128. if (this.onLODLevelSelection) {
  28129. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  28130. }
  28131. return level.mesh;
  28132. }
  28133. }
  28134. if (this.onLODLevelSelection) {
  28135. this.onLODLevelSelection(distanceToCamera, this, this);
  28136. }
  28137. return this;
  28138. };
  28139. Object.defineProperty(Mesh.prototype, "geometry", {
  28140. /**
  28141. * Returns the mesh internal Geometry object.
  28142. */
  28143. get: function () {
  28144. return this._geometry;
  28145. },
  28146. enumerable: true,
  28147. configurable: true
  28148. });
  28149. /**
  28150. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  28151. */
  28152. Mesh.prototype.getTotalVertices = function () {
  28153. if (this._geometry === null || this._geometry === undefined) {
  28154. return 0;
  28155. }
  28156. return this._geometry.getTotalVertices();
  28157. };
  28158. /**
  28159. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  28160. * 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.
  28161. * You can force the copy with forceCopy === true
  28162. * Returns null if the mesh has no geometry or no vertex buffer.
  28163. * Possible `kind` values :
  28164. * - BABYLON.VertexBuffer.PositionKind
  28165. * - BABYLON.VertexBuffer.UVKind
  28166. * - BABYLON.VertexBuffer.UV2Kind
  28167. * - BABYLON.VertexBuffer.UV3Kind
  28168. * - BABYLON.VertexBuffer.UV4Kind
  28169. * - BABYLON.VertexBuffer.UV5Kind
  28170. * - BABYLON.VertexBuffer.UV6Kind
  28171. * - BABYLON.VertexBuffer.ColorKind
  28172. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28173. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28174. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28175. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28176. */
  28177. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28178. if (!this._geometry) {
  28179. return null;
  28180. }
  28181. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  28182. };
  28183. /**
  28184. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  28185. * Returns `null` if the mesh has no geometry.
  28186. * Possible `kind` values :
  28187. * - BABYLON.VertexBuffer.PositionKind
  28188. * - BABYLON.VertexBuffer.UVKind
  28189. * - BABYLON.VertexBuffer.UV2Kind
  28190. * - BABYLON.VertexBuffer.UV3Kind
  28191. * - BABYLON.VertexBuffer.UV4Kind
  28192. * - BABYLON.VertexBuffer.UV5Kind
  28193. * - BABYLON.VertexBuffer.UV6Kind
  28194. * - BABYLON.VertexBuffer.ColorKind
  28195. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28196. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28197. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28198. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28199. */
  28200. Mesh.prototype.getVertexBuffer = function (kind) {
  28201. if (!this._geometry) {
  28202. return null;
  28203. }
  28204. return this._geometry.getVertexBuffer(kind);
  28205. };
  28206. /**
  28207. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  28208. * Possible `kind` values :
  28209. * - BABYLON.VertexBuffer.PositionKind
  28210. * - BABYLON.VertexBuffer.UVKind
  28211. * - BABYLON.VertexBuffer.UV2Kind
  28212. * - BABYLON.VertexBuffer.UV3Kind
  28213. * - BABYLON.VertexBuffer.UV4Kind
  28214. * - BABYLON.VertexBuffer.UV5Kind
  28215. * - BABYLON.VertexBuffer.UV6Kind
  28216. * - BABYLON.VertexBuffer.ColorKind
  28217. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28218. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28219. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28220. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28221. */
  28222. Mesh.prototype.isVerticesDataPresent = function (kind) {
  28223. if (!this._geometry) {
  28224. if (this._delayInfo) {
  28225. return this._delayInfo.indexOf(kind) !== -1;
  28226. }
  28227. return false;
  28228. }
  28229. return this._geometry.isVerticesDataPresent(kind);
  28230. };
  28231. /**
  28232. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  28233. * Possible `kind` values :
  28234. * - BABYLON.VertexBuffer.PositionKind
  28235. * - BABYLON.VertexBuffer.UVKind
  28236. * - BABYLON.VertexBuffer.UV2Kind
  28237. * - BABYLON.VertexBuffer.UV3Kind
  28238. * - BABYLON.VertexBuffer.UV4Kind
  28239. * - BABYLON.VertexBuffer.UV5Kind
  28240. * - BABYLON.VertexBuffer.UV6Kind
  28241. * - BABYLON.VertexBuffer.ColorKind
  28242. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28243. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28244. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28245. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28246. */
  28247. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  28248. if (!this._geometry) {
  28249. if (this._delayInfo) {
  28250. return this._delayInfo.indexOf(kind) !== -1;
  28251. }
  28252. return false;
  28253. }
  28254. return this._geometry.isVertexBufferUpdatable(kind);
  28255. };
  28256. /**
  28257. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  28258. * Possible `kind` values :
  28259. * - BABYLON.VertexBuffer.PositionKind
  28260. * - BABYLON.VertexBuffer.UVKind
  28261. * - BABYLON.VertexBuffer.UV2Kind
  28262. * - BABYLON.VertexBuffer.UV3Kind
  28263. * - BABYLON.VertexBuffer.UV4Kind
  28264. * - BABYLON.VertexBuffer.UV5Kind
  28265. * - BABYLON.VertexBuffer.UV6Kind
  28266. * - BABYLON.VertexBuffer.ColorKind
  28267. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28268. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28269. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28270. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28271. */
  28272. Mesh.prototype.getVerticesDataKinds = function () {
  28273. if (!this._geometry) {
  28274. var result = new Array();
  28275. if (this._delayInfo) {
  28276. this._delayInfo.forEach(function (kind, index, array) {
  28277. result.push(kind);
  28278. });
  28279. }
  28280. return result;
  28281. }
  28282. return this._geometry.getVerticesDataKinds();
  28283. };
  28284. /**
  28285. * Returns a positive integer : the total number of indices in this mesh geometry.
  28286. * Returns zero if the mesh has no geometry.
  28287. */
  28288. Mesh.prototype.getTotalIndices = function () {
  28289. if (!this._geometry) {
  28290. return 0;
  28291. }
  28292. return this._geometry.getTotalIndices();
  28293. };
  28294. /**
  28295. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  28296. * 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.
  28297. * Returns an empty array if the mesh has no geometry.
  28298. */
  28299. Mesh.prototype.getIndices = function (copyWhenShared) {
  28300. if (!this._geometry) {
  28301. return [];
  28302. }
  28303. return this._geometry.getIndices(copyWhenShared);
  28304. };
  28305. Object.defineProperty(Mesh.prototype, "isBlocked", {
  28306. get: function () {
  28307. return this._masterMesh !== null && this._masterMesh !== undefined;
  28308. },
  28309. enumerable: true,
  28310. configurable: true
  28311. });
  28312. /**
  28313. * Determine if the current mesh is ready to be rendered
  28314. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  28315. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  28316. * @returns true if all associated assets are ready (material, textures, shaders)
  28317. */
  28318. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  28319. if (completeCheck === void 0) { completeCheck = false; }
  28320. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  28321. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28322. return false;
  28323. }
  28324. if (!_super.prototype.isReady.call(this, completeCheck)) {
  28325. return false;
  28326. }
  28327. if (!this.subMeshes || this.subMeshes.length === 0) {
  28328. return true;
  28329. }
  28330. if (!completeCheck) {
  28331. return true;
  28332. }
  28333. var engine = this.getEngine();
  28334. var scene = this.getScene();
  28335. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  28336. this.computeWorldMatrix();
  28337. var mat = this.material || scene.defaultMaterial;
  28338. if (mat) {
  28339. if (mat.storeEffectOnSubMeshes) {
  28340. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28341. var subMesh = _a[_i];
  28342. var effectiveMaterial = subMesh.getMaterial();
  28343. if (effectiveMaterial) {
  28344. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28345. return false;
  28346. }
  28347. }
  28348. }
  28349. }
  28350. else {
  28351. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28352. return false;
  28353. }
  28354. }
  28355. }
  28356. // Shadows
  28357. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28358. var light = _c[_b];
  28359. var generator = light.getShadowGenerator();
  28360. if (generator) {
  28361. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28362. var subMesh = _e[_d];
  28363. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28364. return false;
  28365. }
  28366. }
  28367. }
  28368. }
  28369. // LOD
  28370. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28371. var lod = _g[_f];
  28372. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28373. return false;
  28374. }
  28375. }
  28376. return true;
  28377. };
  28378. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28379. /**
  28380. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28381. * This property is pertinent only for updatable parametric shapes.
  28382. */
  28383. get: function () {
  28384. return this._areNormalsFrozen;
  28385. },
  28386. enumerable: true,
  28387. configurable: true
  28388. });
  28389. /**
  28390. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28391. * It has no effect at all on other shapes.
  28392. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28393. * Returns the Mesh.
  28394. */
  28395. Mesh.prototype.freezeNormals = function () {
  28396. this._areNormalsFrozen = true;
  28397. return this;
  28398. };
  28399. /**
  28400. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28401. * It has no effect at all on other shapes.
  28402. * It reactivates the mesh normals computation if it was previously frozen.
  28403. * Returns the Mesh.
  28404. */
  28405. Mesh.prototype.unfreezeNormals = function () {
  28406. this._areNormalsFrozen = false;
  28407. return this;
  28408. };
  28409. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28410. /**
  28411. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28412. */
  28413. set: function (count) {
  28414. this._overridenInstanceCount = count;
  28415. },
  28416. enumerable: true,
  28417. configurable: true
  28418. });
  28419. // Methods
  28420. Mesh.prototype._preActivate = function () {
  28421. var sceneRenderId = this.getScene().getRenderId();
  28422. if (this._preActivateId === sceneRenderId) {
  28423. return this;
  28424. }
  28425. this._preActivateId = sceneRenderId;
  28426. this._visibleInstances = null;
  28427. return this;
  28428. };
  28429. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28430. if (this._visibleInstances) {
  28431. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28432. }
  28433. return this;
  28434. };
  28435. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28436. if (!this._visibleInstances) {
  28437. this._visibleInstances = {};
  28438. this._visibleInstances.defaultRenderId = renderId;
  28439. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28440. }
  28441. if (!this._visibleInstances[renderId]) {
  28442. this._visibleInstances[renderId] = new Array();
  28443. }
  28444. this._visibleInstances[renderId].push(instance);
  28445. return this;
  28446. };
  28447. /**
  28448. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28449. * This means the mesh underlying bounding box and sphere are recomputed.
  28450. * Returns the Mesh.
  28451. */
  28452. Mesh.prototype.refreshBoundingInfo = function () {
  28453. return this._refreshBoundingInfo(false);
  28454. };
  28455. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28456. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28457. return this;
  28458. }
  28459. var data = this._getPositionData(applySkeleton);
  28460. if (data) {
  28461. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28462. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28463. }
  28464. if (this.subMeshes) {
  28465. for (var index = 0; index < this.subMeshes.length; index++) {
  28466. this.subMeshes[index].refreshBoundingInfo();
  28467. }
  28468. }
  28469. this._updateBoundingInfo();
  28470. return this;
  28471. };
  28472. Mesh.prototype._getPositionData = function (applySkeleton) {
  28473. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28474. if (data && applySkeleton && this.skeleton) {
  28475. data = BABYLON.Tools.Slice(data);
  28476. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28477. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28478. if (matricesWeightsData && matricesIndicesData) {
  28479. var needExtras = this.numBoneInfluencers > 4;
  28480. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28481. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28482. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28483. var tempVector = BABYLON.Tmp.Vector3[0];
  28484. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28485. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28486. var matWeightIdx = 0;
  28487. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28488. finalMatrix.reset();
  28489. var inf;
  28490. var weight;
  28491. for (inf = 0; inf < 4; inf++) {
  28492. weight = matricesWeightsData[matWeightIdx + inf];
  28493. if (weight <= 0)
  28494. break;
  28495. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28496. finalMatrix.addToSelf(tempMatrix);
  28497. }
  28498. if (needExtras) {
  28499. for (inf = 0; inf < 4; inf++) {
  28500. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28501. if (weight <= 0)
  28502. break;
  28503. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28504. finalMatrix.addToSelf(tempMatrix);
  28505. }
  28506. }
  28507. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28508. tempVector.toArray(data, index);
  28509. }
  28510. }
  28511. }
  28512. return data;
  28513. };
  28514. Mesh.prototype._createGlobalSubMesh = function (force) {
  28515. var totalVertices = this.getTotalVertices();
  28516. if (!totalVertices || !this.getIndices()) {
  28517. return null;
  28518. }
  28519. // Check if we need to recreate the submeshes
  28520. if (this.subMeshes && this.subMeshes.length > 0) {
  28521. var ib = this.getIndices();
  28522. if (!ib) {
  28523. return null;
  28524. }
  28525. var totalIndices = ib.length;
  28526. var needToRecreate = false;
  28527. if (force) {
  28528. needToRecreate = true;
  28529. }
  28530. else {
  28531. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28532. var submesh = _a[_i];
  28533. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28534. needToRecreate = true;
  28535. break;
  28536. }
  28537. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28538. needToRecreate = true;
  28539. break;
  28540. }
  28541. }
  28542. }
  28543. if (!needToRecreate) {
  28544. return this.subMeshes[0];
  28545. }
  28546. }
  28547. this.releaseSubMeshes();
  28548. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28549. };
  28550. Mesh.prototype.subdivide = function (count) {
  28551. if (count < 1) {
  28552. return;
  28553. }
  28554. var totalIndices = this.getTotalIndices();
  28555. var subdivisionSize = (totalIndices / count) | 0;
  28556. var offset = 0;
  28557. // Ensure that subdivisionSize is a multiple of 3
  28558. while (subdivisionSize % 3 !== 0) {
  28559. subdivisionSize++;
  28560. }
  28561. this.releaseSubMeshes();
  28562. for (var index = 0; index < count; index++) {
  28563. if (offset >= totalIndices) {
  28564. break;
  28565. }
  28566. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28567. offset += subdivisionSize;
  28568. }
  28569. this.synchronizeInstances();
  28570. };
  28571. /**
  28572. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28573. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28574. * The `data` are either a numeric array either a Float32Array.
  28575. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28576. * 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).
  28577. * Note that a new underlying VertexBuffer object is created each call.
  28578. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28579. *
  28580. * Possible `kind` values :
  28581. * - BABYLON.VertexBuffer.PositionKind
  28582. * - BABYLON.VertexBuffer.UVKind
  28583. * - BABYLON.VertexBuffer.UV2Kind
  28584. * - BABYLON.VertexBuffer.UV3Kind
  28585. * - BABYLON.VertexBuffer.UV4Kind
  28586. * - BABYLON.VertexBuffer.UV5Kind
  28587. * - BABYLON.VertexBuffer.UV6Kind
  28588. * - BABYLON.VertexBuffer.ColorKind
  28589. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28590. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28591. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28592. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28593. *
  28594. * Returns the Mesh.
  28595. */
  28596. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28597. if (updatable === void 0) { updatable = false; }
  28598. if (!this._geometry) {
  28599. var vertexData = new BABYLON.VertexData();
  28600. vertexData.set(data, kind);
  28601. var scene = this.getScene();
  28602. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28603. }
  28604. else {
  28605. this._geometry.setVerticesData(kind, data, updatable, stride);
  28606. }
  28607. return this;
  28608. };
  28609. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28610. if (updatable === void 0) { updatable = true; }
  28611. var vb = this.getVertexBuffer(kind);
  28612. if (!vb || vb.isUpdatable() === updatable) {
  28613. return;
  28614. }
  28615. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28616. };
  28617. /**
  28618. * Sets the mesh VertexBuffer.
  28619. * Returns the Mesh.
  28620. */
  28621. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28622. if (!this._geometry) {
  28623. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28624. }
  28625. this._geometry.setVerticesBuffer(buffer);
  28626. return this;
  28627. };
  28628. /**
  28629. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28630. * If the mesh has no geometry, it is simply returned as it is.
  28631. * The `data` are either a numeric array either a Float32Array.
  28632. * No new underlying VertexBuffer object is created.
  28633. * 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.
  28634. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28635. *
  28636. * Possible `kind` values :
  28637. * - BABYLON.VertexBuffer.PositionKind
  28638. * - BABYLON.VertexBuffer.UVKind
  28639. * - BABYLON.VertexBuffer.UV2Kind
  28640. * - BABYLON.VertexBuffer.UV3Kind
  28641. * - BABYLON.VertexBuffer.UV4Kind
  28642. * - BABYLON.VertexBuffer.UV5Kind
  28643. * - BABYLON.VertexBuffer.UV6Kind
  28644. * - BABYLON.VertexBuffer.ColorKind
  28645. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28646. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28647. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28648. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28649. *
  28650. * Returns the Mesh.
  28651. */
  28652. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28653. if (!this._geometry) {
  28654. return this;
  28655. }
  28656. if (!makeItUnique) {
  28657. this._geometry.updateVerticesData(kind, data, updateExtends);
  28658. }
  28659. else {
  28660. this.makeGeometryUnique();
  28661. this.updateVerticesData(kind, data, updateExtends, false);
  28662. }
  28663. return this;
  28664. };
  28665. /**
  28666. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28667. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28668. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28669. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28670. * Returns the Mesh.
  28671. */
  28672. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28673. if (computeNormals === void 0) { computeNormals = true; }
  28674. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28675. if (!positions) {
  28676. return this;
  28677. }
  28678. positionFunction(positions);
  28679. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28680. if (computeNormals) {
  28681. var indices = this.getIndices();
  28682. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28683. if (!normals) {
  28684. return this;
  28685. }
  28686. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28687. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28688. }
  28689. return this;
  28690. };
  28691. /**
  28692. * Creates a un-shared specific occurence of the geometry for the mesh.
  28693. * Returns the Mesh.
  28694. */
  28695. Mesh.prototype.makeGeometryUnique = function () {
  28696. if (!this._geometry) {
  28697. return this;
  28698. }
  28699. var oldGeometry = this._geometry;
  28700. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28701. oldGeometry.releaseForMesh(this, true);
  28702. geometry.applyToMesh(this);
  28703. return this;
  28704. };
  28705. /**
  28706. * Sets the mesh indices.
  28707. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28708. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28709. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28710. * This method creates a new index buffer each call.
  28711. * Returns the Mesh.
  28712. */
  28713. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28714. if (totalVertices === void 0) { totalVertices = null; }
  28715. if (updatable === void 0) { updatable = false; }
  28716. if (!this._geometry) {
  28717. var vertexData = new BABYLON.VertexData();
  28718. vertexData.indices = indices;
  28719. var scene = this.getScene();
  28720. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28721. }
  28722. else {
  28723. this._geometry.setIndices(indices, totalVertices, updatable);
  28724. }
  28725. return this;
  28726. };
  28727. /**
  28728. * Update the current index buffer
  28729. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28730. * Returns the Mesh.
  28731. */
  28732. Mesh.prototype.updateIndices = function (indices, offset) {
  28733. if (!this._geometry) {
  28734. return this;
  28735. }
  28736. this._geometry.updateIndices(indices, offset);
  28737. return this;
  28738. };
  28739. /**
  28740. * Invert the geometry to move from a right handed system to a left handed one.
  28741. * Returns the Mesh.
  28742. */
  28743. Mesh.prototype.toLeftHanded = function () {
  28744. if (!this._geometry) {
  28745. return this;
  28746. }
  28747. this._geometry.toLeftHanded();
  28748. return this;
  28749. };
  28750. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28751. if (!this._geometry) {
  28752. return this;
  28753. }
  28754. var engine = this.getScene().getEngine();
  28755. // Wireframe
  28756. var indexToBind;
  28757. if (this._unIndexed) {
  28758. indexToBind = null;
  28759. }
  28760. else {
  28761. switch (fillMode) {
  28762. case BABYLON.Material.PointFillMode:
  28763. indexToBind = null;
  28764. break;
  28765. case BABYLON.Material.WireFrameFillMode:
  28766. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28767. break;
  28768. default:
  28769. case BABYLON.Material.TriangleFillMode:
  28770. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28771. break;
  28772. }
  28773. }
  28774. // VBOs
  28775. this._geometry._bind(effect, indexToBind);
  28776. return this;
  28777. };
  28778. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28779. if (alternate === void 0) { alternate = false; }
  28780. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28781. return this;
  28782. }
  28783. this.onBeforeDrawObservable.notifyObservers(this);
  28784. var scene = this.getScene();
  28785. var engine = scene.getEngine();
  28786. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28787. // or triangles as points
  28788. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28789. }
  28790. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28791. // Triangles as wireframe
  28792. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28793. }
  28794. else {
  28795. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28796. }
  28797. if (scene._isAlternateRenderingEnabled && !alternate) {
  28798. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28799. if (!effect || !scene.activeCamera) {
  28800. return this;
  28801. }
  28802. scene._switchToAlternateCameraConfiguration(true);
  28803. this._effectiveMaterial.bindView(effect);
  28804. this._effectiveMaterial.bindViewProjection(effect);
  28805. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28806. this._draw(subMesh, fillMode, instancesCount, true);
  28807. engine.setViewport(scene.activeCamera.viewport);
  28808. scene._switchToAlternateCameraConfiguration(false);
  28809. this._effectiveMaterial.bindView(effect);
  28810. this._effectiveMaterial.bindViewProjection(effect);
  28811. }
  28812. return this;
  28813. };
  28814. /**
  28815. * Registers for this mesh a javascript function called just before the rendering process.
  28816. * This function is passed the current mesh.
  28817. * Return the Mesh.
  28818. */
  28819. Mesh.prototype.registerBeforeRender = function (func) {
  28820. this.onBeforeRenderObservable.add(func);
  28821. return this;
  28822. };
  28823. /**
  28824. * Disposes a previously registered javascript function called before the rendering.
  28825. * This function is passed the current mesh.
  28826. * Returns the Mesh.
  28827. */
  28828. Mesh.prototype.unregisterBeforeRender = function (func) {
  28829. this.onBeforeRenderObservable.removeCallback(func);
  28830. return this;
  28831. };
  28832. /**
  28833. * Registers for this mesh a javascript function called just after the rendering is complete.
  28834. * This function is passed the current mesh.
  28835. * Returns the Mesh.
  28836. */
  28837. Mesh.prototype.registerAfterRender = function (func) {
  28838. this.onAfterRenderObservable.add(func);
  28839. return this;
  28840. };
  28841. /**
  28842. * Disposes a previously registered javascript function called after the rendering.
  28843. * This function is passed the current mesh.
  28844. * Return the Mesh.
  28845. */
  28846. Mesh.prototype.unregisterAfterRender = function (func) {
  28847. this.onAfterRenderObservable.removeCallback(func);
  28848. return this;
  28849. };
  28850. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28851. var scene = this.getScene();
  28852. this._batchCache.mustReturn = false;
  28853. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28854. this._batchCache.visibleInstances[subMeshId] = null;
  28855. if (this._visibleInstances) {
  28856. var currentRenderId = scene.getRenderId();
  28857. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28858. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28859. var selfRenderId = this._renderId;
  28860. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28861. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28862. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28863. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28864. }
  28865. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28866. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28867. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28868. this._batchCache.mustReturn = true;
  28869. return this._batchCache;
  28870. }
  28871. if (currentRenderId !== selfRenderId) {
  28872. this._batchCache.renderSelf[subMeshId] = false;
  28873. }
  28874. }
  28875. this._renderIdForInstances[subMeshId] = currentRenderId;
  28876. }
  28877. return this._batchCache;
  28878. };
  28879. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28880. var visibleInstances = batch.visibleInstances[subMesh._id];
  28881. if (!visibleInstances) {
  28882. return this;
  28883. }
  28884. var matricesCount = visibleInstances.length + 1;
  28885. var bufferSize = matricesCount * 16 * 4;
  28886. var currentInstancesBufferSize = this._instancesBufferSize;
  28887. var instancesBuffer = this._instancesBuffer;
  28888. while (this._instancesBufferSize < bufferSize) {
  28889. this._instancesBufferSize *= 2;
  28890. }
  28891. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28892. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28893. }
  28894. var offset = 0;
  28895. var instancesCount = 0;
  28896. var world = this.getWorldMatrix();
  28897. if (batch.renderSelf[subMesh._id]) {
  28898. world.copyToArray(this._instancesData, offset);
  28899. offset += 16;
  28900. instancesCount++;
  28901. }
  28902. if (visibleInstances) {
  28903. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28904. var instance = visibleInstances[instanceIndex];
  28905. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28906. offset += 16;
  28907. instancesCount++;
  28908. }
  28909. }
  28910. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28911. if (instancesBuffer) {
  28912. instancesBuffer.dispose();
  28913. }
  28914. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28915. this._instancesBuffer = instancesBuffer;
  28916. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28917. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28918. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28919. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28920. }
  28921. else {
  28922. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28923. }
  28924. this._bind(subMesh, effect, fillMode);
  28925. this._draw(subMesh, fillMode, instancesCount);
  28926. engine.unbindInstanceAttributes();
  28927. return this;
  28928. };
  28929. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28930. var scene = this.getScene();
  28931. var engine = scene.getEngine();
  28932. if (hardwareInstancedRendering) {
  28933. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28934. }
  28935. else {
  28936. if (batch.renderSelf[subMesh._id]) {
  28937. // Draw
  28938. if (onBeforeDraw) {
  28939. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28940. }
  28941. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28942. }
  28943. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28944. if (visibleInstancesForSubMesh) {
  28945. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28946. var instance = visibleInstancesForSubMesh[instanceIndex];
  28947. // World
  28948. var world = instance.getWorldMatrix();
  28949. if (onBeforeDraw) {
  28950. onBeforeDraw(true, world, effectiveMaterial);
  28951. }
  28952. // Draw
  28953. this._draw(subMesh, fillMode);
  28954. }
  28955. }
  28956. }
  28957. return this;
  28958. };
  28959. /**
  28960. * Triggers the draw call for the mesh.
  28961. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28962. * Returns the Mesh.
  28963. */
  28964. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28965. this.checkOcclusionQuery();
  28966. if (this._isOccluded) {
  28967. return this;
  28968. }
  28969. var scene = this.getScene();
  28970. // Managing instances
  28971. var batch = this._getInstancesRenderList(subMesh._id);
  28972. if (batch.mustReturn) {
  28973. return this;
  28974. }
  28975. // Checking geometry state
  28976. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28977. return this;
  28978. }
  28979. this.onBeforeRenderObservable.notifyObservers(this);
  28980. var engine = scene.getEngine();
  28981. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28982. // Material
  28983. var material = subMesh.getMaterial();
  28984. if (!material) {
  28985. return this;
  28986. }
  28987. this._effectiveMaterial = material;
  28988. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28989. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28990. return this;
  28991. }
  28992. }
  28993. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28994. return this;
  28995. }
  28996. // Alpha mode
  28997. if (enableAlphaMode) {
  28998. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28999. }
  29000. // Outline - step 1
  29001. var savedDepthWrite = engine.getDepthWrite();
  29002. if (this.renderOutline) {
  29003. engine.setDepthWrite(false);
  29004. scene.getOutlineRenderer().render(subMesh, batch);
  29005. engine.setDepthWrite(savedDepthWrite);
  29006. }
  29007. var effect;
  29008. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29009. effect = subMesh.effect;
  29010. }
  29011. else {
  29012. effect = this._effectiveMaterial.getEffect();
  29013. }
  29014. if (!effect) {
  29015. return this;
  29016. }
  29017. var sideOrientation = this.overrideMaterialSideOrientation;
  29018. if (sideOrientation == null) {
  29019. sideOrientation = this._effectiveMaterial.sideOrientation;
  29020. if (this._getWorldMatrixDeterminant() < 0) {
  29021. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  29022. }
  29023. }
  29024. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  29025. if (this._effectiveMaterial.forceDepthWrite) {
  29026. engine.setDepthWrite(true);
  29027. }
  29028. // Bind
  29029. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  29030. if (!hardwareInstancedRendering) {
  29031. this._bind(subMesh, effect, fillMode);
  29032. }
  29033. var world = this.getWorldMatrix();
  29034. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29035. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  29036. }
  29037. else {
  29038. this._effectiveMaterial.bind(world, this);
  29039. }
  29040. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  29041. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  29042. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29043. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  29044. }
  29045. // Draw
  29046. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29047. // Unbind
  29048. this._effectiveMaterial.unbind();
  29049. // Outline - step 2
  29050. if (this.renderOutline && savedDepthWrite) {
  29051. engine.setDepthWrite(true);
  29052. engine.setColorWrite(false);
  29053. scene.getOutlineRenderer().render(subMesh, batch);
  29054. engine.setColorWrite(true);
  29055. }
  29056. // Overlay
  29057. if (this.renderOverlay) {
  29058. var currentMode = engine.getAlphaMode();
  29059. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29060. scene.getOutlineRenderer().render(subMesh, batch, true);
  29061. engine.setAlphaMode(currentMode);
  29062. }
  29063. this.onAfterRenderObservable.notifyObservers(this);
  29064. return this;
  29065. };
  29066. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  29067. if (isInstance && effectiveMaterial) {
  29068. effectiveMaterial.bindOnlyWorldMatrix(world);
  29069. }
  29070. };
  29071. /**
  29072. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  29073. */
  29074. Mesh.prototype.getEmittedParticleSystems = function () {
  29075. var results = new Array();
  29076. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29077. var particleSystem = this.getScene().particleSystems[index];
  29078. if (particleSystem.emitter === this) {
  29079. results.push(particleSystem);
  29080. }
  29081. }
  29082. return results;
  29083. };
  29084. /**
  29085. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  29086. */
  29087. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  29088. var results = new Array();
  29089. var descendants = this.getDescendants();
  29090. descendants.push(this);
  29091. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29092. var particleSystem = this.getScene().particleSystems[index];
  29093. var emitter = particleSystem.emitter;
  29094. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  29095. results.push(particleSystem);
  29096. }
  29097. }
  29098. return results;
  29099. };
  29100. Mesh.prototype._checkDelayState = function () {
  29101. var scene = this.getScene();
  29102. if (this._geometry) {
  29103. this._geometry.load(scene);
  29104. }
  29105. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29106. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29107. this._queueLoad(scene);
  29108. }
  29109. return this;
  29110. };
  29111. Mesh.prototype._queueLoad = function (scene) {
  29112. var _this = this;
  29113. scene._addPendingData(this);
  29114. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  29115. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29116. if (data instanceof ArrayBuffer) {
  29117. _this._delayLoadingFunction(data, _this);
  29118. }
  29119. else {
  29120. _this._delayLoadingFunction(JSON.parse(data), _this);
  29121. }
  29122. _this.instances.forEach(function (instance) {
  29123. instance._syncSubMeshes();
  29124. });
  29125. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29126. scene._removePendingData(_this);
  29127. }, function () { }, scene.database, getBinaryData);
  29128. return this;
  29129. };
  29130. /**
  29131. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  29132. */
  29133. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  29134. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29135. return false;
  29136. }
  29137. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  29138. return false;
  29139. }
  29140. this._checkDelayState();
  29141. return true;
  29142. };
  29143. /**
  29144. * Sets the mesh material by the material or multiMaterial `id` property.
  29145. * The material `id` is a string identifying the material or the multiMaterial.
  29146. * This method returns the Mesh.
  29147. */
  29148. Mesh.prototype.setMaterialByID = function (id) {
  29149. var materials = this.getScene().materials;
  29150. var index;
  29151. for (index = materials.length - 1; index > -1; index--) {
  29152. if (materials[index].id === id) {
  29153. this.material = materials[index];
  29154. return this;
  29155. }
  29156. }
  29157. // Multi
  29158. var multiMaterials = this.getScene().multiMaterials;
  29159. for (index = multiMaterials.length - 1; index > -1; index--) {
  29160. if (multiMaterials[index].id === id) {
  29161. this.material = multiMaterials[index];
  29162. return this;
  29163. }
  29164. }
  29165. return this;
  29166. };
  29167. /**
  29168. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  29169. */
  29170. Mesh.prototype.getAnimatables = function () {
  29171. var results = new Array();
  29172. if (this.material) {
  29173. results.push(this.material);
  29174. }
  29175. if (this.skeleton) {
  29176. results.push(this.skeleton);
  29177. }
  29178. return results;
  29179. };
  29180. /**
  29181. * Modifies the mesh geometry according to the passed transformation matrix.
  29182. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  29183. * The mesh normals are modified accordingly the same transformation.
  29184. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  29185. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29186. * Returns the Mesh.
  29187. */
  29188. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  29189. // Position
  29190. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29191. return this;
  29192. }
  29193. var submeshes = this.subMeshes.splice(0);
  29194. this._resetPointsArrayCache();
  29195. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29196. var temp = new Array();
  29197. var index;
  29198. for (index = 0; index < data.length; index += 3) {
  29199. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  29200. }
  29201. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  29202. // Normals
  29203. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29204. return this;
  29205. }
  29206. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29207. temp = [];
  29208. for (index = 0; index < data.length; index += 3) {
  29209. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  29210. }
  29211. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  29212. // flip faces?
  29213. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  29214. this.flipFaces();
  29215. }
  29216. // Restore submeshes
  29217. this.releaseSubMeshes();
  29218. this.subMeshes = submeshes;
  29219. return this;
  29220. };
  29221. /**
  29222. * Modifies the mesh geometry according to its own current World Matrix.
  29223. * The mesh World Matrix is then reset.
  29224. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  29225. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  29226. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29227. * Returns the Mesh.
  29228. */
  29229. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  29230. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  29231. this.scaling.copyFromFloats(1, 1, 1);
  29232. this.position.copyFromFloats(0, 0, 0);
  29233. this.rotation.copyFromFloats(0, 0, 0);
  29234. //only if quaternion is already set
  29235. if (this.rotationQuaternion) {
  29236. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  29237. }
  29238. this._worldMatrix = BABYLON.Matrix.Identity();
  29239. return this;
  29240. };
  29241. Object.defineProperty(Mesh.prototype, "_positions", {
  29242. // Cache
  29243. get: function () {
  29244. if (this._geometry) {
  29245. return this._geometry._positions;
  29246. }
  29247. return null;
  29248. },
  29249. enumerable: true,
  29250. configurable: true
  29251. });
  29252. Mesh.prototype._resetPointsArrayCache = function () {
  29253. if (this._geometry) {
  29254. this._geometry._resetPointsArrayCache();
  29255. }
  29256. return this;
  29257. };
  29258. Mesh.prototype._generatePointsArray = function () {
  29259. if (this._geometry) {
  29260. return this._geometry._generatePointsArray();
  29261. }
  29262. return false;
  29263. };
  29264. /**
  29265. * Returns a new Mesh object generated from the current mesh properties.
  29266. * This method must not get confused with createInstance().
  29267. * The parameter `name` is a string, the name given to the new mesh.
  29268. * The optional parameter `newParent` can be any Node object (default `null`).
  29269. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  29270. * 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.
  29271. */
  29272. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  29273. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  29274. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  29275. };
  29276. /**
  29277. * Releases resources associated with this mesh.
  29278. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  29279. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  29280. */
  29281. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  29282. var _this = this;
  29283. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  29284. this.morphTargetManager = null;
  29285. if (this._geometry) {
  29286. this._geometry.releaseForMesh(this, true);
  29287. }
  29288. // Sources
  29289. var meshes = this.getScene().meshes;
  29290. meshes.forEach(function (abstractMesh) {
  29291. var mesh = abstractMesh;
  29292. if (mesh._source && mesh._source === _this) {
  29293. mesh._source = null;
  29294. }
  29295. });
  29296. this._source = null;
  29297. // Instances
  29298. if (this._instancesBuffer) {
  29299. this._instancesBuffer.dispose();
  29300. this._instancesBuffer = null;
  29301. }
  29302. while (this.instances.length) {
  29303. this.instances[0].dispose();
  29304. }
  29305. // Effect layers.
  29306. var effectLayers = this.getScene().effectLayers;
  29307. for (var i = 0; i < effectLayers.length; i++) {
  29308. var effectLayer = effectLayers[i];
  29309. if (effectLayer) {
  29310. effectLayer._disposeMesh(this);
  29311. }
  29312. }
  29313. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  29314. };
  29315. /**
  29316. * Modifies the mesh geometry according to a displacement map.
  29317. * 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.
  29318. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29319. * This method returns nothing.
  29320. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  29321. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29322. * 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.
  29323. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29324. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29325. *
  29326. * Returns the Mesh.
  29327. */
  29328. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  29329. var _this = this;
  29330. var scene = this.getScene();
  29331. var onload = function (img) {
  29332. // Getting height map data
  29333. var canvas = document.createElement("canvas");
  29334. var context = canvas.getContext("2d");
  29335. var heightMapWidth = img.width;
  29336. var heightMapHeight = img.height;
  29337. canvas.width = heightMapWidth;
  29338. canvas.height = heightMapHeight;
  29339. context.drawImage(img, 0, 0);
  29340. // Create VertexData from map data
  29341. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29342. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  29343. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  29344. //execute success callback, if set
  29345. if (onSuccess) {
  29346. onSuccess(_this);
  29347. }
  29348. };
  29349. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29350. return this;
  29351. };
  29352. /**
  29353. * Modifies the mesh geometry according to a displacementMap buffer.
  29354. * 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.
  29355. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29356. * This method returns nothing.
  29357. * 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.
  29358. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29359. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29360. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29361. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29362. *
  29363. * Returns the Mesh.
  29364. */
  29365. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29366. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29367. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29368. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29369. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29370. return this;
  29371. }
  29372. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29373. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29374. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29375. var position = BABYLON.Vector3.Zero();
  29376. var normal = BABYLON.Vector3.Zero();
  29377. var uv = BABYLON.Vector2.Zero();
  29378. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29379. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29380. for (var index = 0; index < positions.length; index += 3) {
  29381. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29382. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29383. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29384. // Compute height
  29385. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29386. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29387. var pos = (u + v * heightMapWidth) * 4;
  29388. var r = buffer[pos] / 255.0;
  29389. var g = buffer[pos + 1] / 255.0;
  29390. var b = buffer[pos + 2] / 255.0;
  29391. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29392. normal.normalize();
  29393. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29394. position = position.add(normal);
  29395. position.toArray(positions, index);
  29396. }
  29397. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29398. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29399. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29400. return this;
  29401. };
  29402. /**
  29403. * Modify the mesh to get a flat shading rendering.
  29404. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29405. * This method returns the Mesh.
  29406. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29407. */
  29408. Mesh.prototype.convertToFlatShadedMesh = function () {
  29409. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29410. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29411. var kinds = this.getVerticesDataKinds();
  29412. var vbs = {};
  29413. var data = {};
  29414. var newdata = {};
  29415. var updatableNormals = false;
  29416. var kindIndex;
  29417. var kind;
  29418. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29419. kind = kinds[kindIndex];
  29420. var vertexBuffer = this.getVertexBuffer(kind);
  29421. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29422. updatableNormals = vertexBuffer.isUpdatable();
  29423. kinds.splice(kindIndex, 1);
  29424. kindIndex--;
  29425. continue;
  29426. }
  29427. vbs[kind] = vertexBuffer;
  29428. data[kind] = vbs[kind].getData();
  29429. newdata[kind] = [];
  29430. }
  29431. // Save previous submeshes
  29432. var previousSubmeshes = this.subMeshes.slice(0);
  29433. var indices = this.getIndices();
  29434. var totalIndices = this.getTotalIndices();
  29435. // Generating unique vertices per face
  29436. var index;
  29437. for (index = 0; index < totalIndices; index++) {
  29438. var vertexIndex = indices[index];
  29439. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29440. kind = kinds[kindIndex];
  29441. var stride = vbs[kind].getStrideSize();
  29442. for (var offset = 0; offset < stride; offset++) {
  29443. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29444. }
  29445. }
  29446. }
  29447. // Updating faces & normal
  29448. var normals = [];
  29449. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29450. for (index = 0; index < totalIndices; index += 3) {
  29451. indices[index] = index;
  29452. indices[index + 1] = index + 1;
  29453. indices[index + 2] = index + 2;
  29454. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29455. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29456. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29457. var p1p2 = p1.subtract(p2);
  29458. var p3p2 = p3.subtract(p2);
  29459. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29460. // Store same normals for every vertex
  29461. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29462. normals.push(normal.x);
  29463. normals.push(normal.y);
  29464. normals.push(normal.z);
  29465. }
  29466. }
  29467. this.setIndices(indices);
  29468. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29469. // Updating vertex buffers
  29470. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29471. kind = kinds[kindIndex];
  29472. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29473. }
  29474. // Updating submeshes
  29475. this.releaseSubMeshes();
  29476. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29477. var previousOne = previousSubmeshes[submeshIndex];
  29478. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29479. }
  29480. this.synchronizeInstances();
  29481. return this;
  29482. };
  29483. /**
  29484. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29485. * In other words, more vertices, no more indices and a single bigger VBO.
  29486. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29487. * Returns the Mesh.
  29488. */
  29489. Mesh.prototype.convertToUnIndexedMesh = function () {
  29490. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29491. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29492. var kinds = this.getVerticesDataKinds();
  29493. var vbs = {};
  29494. var data = {};
  29495. var newdata = {};
  29496. var kindIndex;
  29497. var kind;
  29498. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29499. kind = kinds[kindIndex];
  29500. var vertexBuffer = this.getVertexBuffer(kind);
  29501. vbs[kind] = vertexBuffer;
  29502. data[kind] = vbs[kind].getData();
  29503. newdata[kind] = [];
  29504. }
  29505. // Save previous submeshes
  29506. var previousSubmeshes = this.subMeshes.slice(0);
  29507. var indices = this.getIndices();
  29508. var totalIndices = this.getTotalIndices();
  29509. // Generating unique vertices per face
  29510. var index;
  29511. for (index = 0; index < totalIndices; index++) {
  29512. var vertexIndex = indices[index];
  29513. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29514. kind = kinds[kindIndex];
  29515. var stride = vbs[kind].getStrideSize();
  29516. for (var offset = 0; offset < stride; offset++) {
  29517. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29518. }
  29519. }
  29520. }
  29521. // Updating indices
  29522. for (index = 0; index < totalIndices; index += 3) {
  29523. indices[index] = index;
  29524. indices[index + 1] = index + 1;
  29525. indices[index + 2] = index + 2;
  29526. }
  29527. this.setIndices(indices);
  29528. // Updating vertex buffers
  29529. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29530. kind = kinds[kindIndex];
  29531. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29532. }
  29533. // Updating submeshes
  29534. this.releaseSubMeshes();
  29535. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29536. var previousOne = previousSubmeshes[submeshIndex];
  29537. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29538. }
  29539. this._unIndexed = true;
  29540. this.synchronizeInstances();
  29541. return this;
  29542. };
  29543. /**
  29544. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29545. * This method returns the Mesh.
  29546. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29547. */
  29548. Mesh.prototype.flipFaces = function (flipNormals) {
  29549. if (flipNormals === void 0) { flipNormals = false; }
  29550. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29551. var i;
  29552. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29553. for (i = 0; i < vertex_data.normals.length; i++) {
  29554. vertex_data.normals[i] *= -1;
  29555. }
  29556. }
  29557. if (vertex_data.indices) {
  29558. var temp;
  29559. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29560. // reassign indices
  29561. temp = vertex_data.indices[i + 1];
  29562. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29563. vertex_data.indices[i + 2] = temp;
  29564. }
  29565. }
  29566. vertex_data.applyToMesh(this);
  29567. return this;
  29568. };
  29569. // Instances
  29570. /**
  29571. * Creates a new InstancedMesh object from the mesh model.
  29572. * An instance shares the same properties and the same material than its model.
  29573. * Only these properties of each instance can then be set individually :
  29574. * - position
  29575. * - rotation
  29576. * - rotationQuaternion
  29577. * - setPivotMatrix
  29578. * - scaling
  29579. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29580. * Warning : this method is not supported for Line mesh and LineSystem
  29581. */
  29582. Mesh.prototype.createInstance = function (name) {
  29583. return new BABYLON.InstancedMesh(name, this);
  29584. };
  29585. /**
  29586. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29587. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29588. * This method returns the Mesh.
  29589. */
  29590. Mesh.prototype.synchronizeInstances = function () {
  29591. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29592. var instance = this.instances[instanceIndex];
  29593. instance._syncSubMeshes();
  29594. }
  29595. return this;
  29596. };
  29597. /**
  29598. * Simplify the mesh according to the given array of settings.
  29599. * Function will return immediately and will simplify async. It returns the Mesh.
  29600. * @param settings a collection of simplification settings.
  29601. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29602. * @param type the type of simplification to run.
  29603. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29604. */
  29605. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29606. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29607. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29608. this.getScene().simplificationQueue.addTask({
  29609. settings: settings,
  29610. parallelProcessing: parallelProcessing,
  29611. mesh: this,
  29612. simplificationType: simplificationType,
  29613. successCallback: successCallback
  29614. });
  29615. return this;
  29616. };
  29617. /**
  29618. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29619. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29620. * This should be used together with the simplification to avoid disappearing triangles.
  29621. * Returns the Mesh.
  29622. * @param successCallback an optional success callback to be called after the optimization finished.
  29623. */
  29624. Mesh.prototype.optimizeIndices = function (successCallback) {
  29625. var _this = this;
  29626. var indices = this.getIndices();
  29627. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29628. if (!positions || !indices) {
  29629. return this;
  29630. }
  29631. var vectorPositions = new Array();
  29632. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29633. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29634. }
  29635. var dupes = new Array();
  29636. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29637. var realPos = vectorPositions.length - 1 - iteration;
  29638. var testedPosition = vectorPositions[realPos];
  29639. for (var j = 0; j < realPos; ++j) {
  29640. var againstPosition = vectorPositions[j];
  29641. if (testedPosition.equals(againstPosition)) {
  29642. dupes[realPos] = j;
  29643. break;
  29644. }
  29645. }
  29646. }, function () {
  29647. for (var i = 0; i < indices.length; ++i) {
  29648. indices[i] = dupes[indices[i]] || indices[i];
  29649. }
  29650. //indices are now reordered
  29651. var originalSubMeshes = _this.subMeshes.slice(0);
  29652. _this.setIndices(indices);
  29653. _this.subMeshes = originalSubMeshes;
  29654. if (successCallback) {
  29655. successCallback(_this);
  29656. }
  29657. });
  29658. return this;
  29659. };
  29660. Mesh.prototype.serialize = function (serializationObject) {
  29661. serializationObject.name = this.name;
  29662. serializationObject.id = this.id;
  29663. serializationObject.type = this.getClassName();
  29664. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29665. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29666. }
  29667. serializationObject.position = this.position.asArray();
  29668. if (this.rotationQuaternion) {
  29669. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29670. }
  29671. else if (this.rotation) {
  29672. serializationObject.rotation = this.rotation.asArray();
  29673. }
  29674. serializationObject.scaling = this.scaling.asArray();
  29675. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29676. serializationObject.isEnabled = this.isEnabled(false);
  29677. serializationObject.isVisible = this.isVisible;
  29678. serializationObject.infiniteDistance = this.infiniteDistance;
  29679. serializationObject.pickable = this.isPickable;
  29680. serializationObject.receiveShadows = this.receiveShadows;
  29681. serializationObject.billboardMode = this.billboardMode;
  29682. serializationObject.visibility = this.visibility;
  29683. serializationObject.checkCollisions = this.checkCollisions;
  29684. serializationObject.isBlocker = this.isBlocker;
  29685. // Parent
  29686. if (this.parent) {
  29687. serializationObject.parentId = this.parent.id;
  29688. }
  29689. // Geometry
  29690. serializationObject.isUnIndexed = this.isUnIndexed;
  29691. var geometry = this._geometry;
  29692. if (geometry) {
  29693. var geometryId = geometry.id;
  29694. serializationObject.geometryId = geometryId;
  29695. // SubMeshes
  29696. serializationObject.subMeshes = [];
  29697. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29698. var subMesh = this.subMeshes[subIndex];
  29699. serializationObject.subMeshes.push({
  29700. materialIndex: subMesh.materialIndex,
  29701. verticesStart: subMesh.verticesStart,
  29702. verticesCount: subMesh.verticesCount,
  29703. indexStart: subMesh.indexStart,
  29704. indexCount: subMesh.indexCount
  29705. });
  29706. }
  29707. }
  29708. // Material
  29709. if (this.material) {
  29710. serializationObject.materialId = this.material.id;
  29711. }
  29712. else {
  29713. this.material = null;
  29714. }
  29715. // Morph targets
  29716. if (this.morphTargetManager) {
  29717. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29718. }
  29719. // Skeleton
  29720. if (this.skeleton) {
  29721. serializationObject.skeletonId = this.skeleton.id;
  29722. }
  29723. // Physics
  29724. //TODO implement correct serialization for physics impostors.
  29725. var impostor = this.getPhysicsImpostor();
  29726. if (impostor) {
  29727. serializationObject.physicsMass = impostor.getParam("mass");
  29728. serializationObject.physicsFriction = impostor.getParam("friction");
  29729. serializationObject.physicsRestitution = impostor.getParam("mass");
  29730. serializationObject.physicsImpostor = impostor.type;
  29731. }
  29732. // Metadata
  29733. if (this.metadata) {
  29734. serializationObject.metadata = this.metadata;
  29735. }
  29736. // Instances
  29737. serializationObject.instances = [];
  29738. for (var index = 0; index < this.instances.length; index++) {
  29739. var instance = this.instances[index];
  29740. var serializationInstance = {
  29741. name: instance.name,
  29742. id: instance.id,
  29743. position: instance.position.asArray(),
  29744. scaling: instance.scaling.asArray()
  29745. };
  29746. if (instance.rotationQuaternion) {
  29747. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29748. }
  29749. else if (instance.rotation) {
  29750. serializationInstance.rotation = instance.rotation.asArray();
  29751. }
  29752. serializationObject.instances.push(serializationInstance);
  29753. // Animations
  29754. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29755. serializationInstance.ranges = instance.serializeAnimationRanges();
  29756. }
  29757. //
  29758. // Animations
  29759. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29760. serializationObject.ranges = this.serializeAnimationRanges();
  29761. // Layer mask
  29762. serializationObject.layerMask = this.layerMask;
  29763. // Alpha
  29764. serializationObject.alphaIndex = this.alphaIndex;
  29765. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29766. // Overlay
  29767. serializationObject.overlayAlpha = this.overlayAlpha;
  29768. serializationObject.overlayColor = this.overlayColor.asArray();
  29769. serializationObject.renderOverlay = this.renderOverlay;
  29770. // Fog
  29771. serializationObject.applyFog = this.applyFog;
  29772. // Action Manager
  29773. if (this.actionManager) {
  29774. serializationObject.actions = this.actionManager.serialize(this.name);
  29775. }
  29776. };
  29777. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29778. if (!this.geometry) {
  29779. return;
  29780. }
  29781. this._markSubMeshesAsAttributesDirty();
  29782. var morphTargetManager = this._morphTargetManager;
  29783. if (morphTargetManager && morphTargetManager.vertexCount) {
  29784. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29785. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29786. this.morphTargetManager = null;
  29787. return;
  29788. }
  29789. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29790. var morphTarget = morphTargetManager.getActiveTarget(index);
  29791. var positions = morphTarget.getPositions();
  29792. if (!positions) {
  29793. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29794. return;
  29795. }
  29796. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29797. var normals = morphTarget.getNormals();
  29798. if (normals) {
  29799. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29800. }
  29801. var tangents = morphTarget.getTangents();
  29802. if (tangents) {
  29803. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29804. }
  29805. }
  29806. }
  29807. else {
  29808. var index = 0;
  29809. // Positions
  29810. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29811. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29812. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29813. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29814. }
  29815. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29816. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29817. }
  29818. index++;
  29819. }
  29820. }
  29821. };
  29822. // Statics
  29823. /**
  29824. * Returns a new Mesh object parsed from the source provided.
  29825. * The parameter `parsedMesh` is the source.
  29826. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29827. */
  29828. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29829. var mesh;
  29830. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29831. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29832. }
  29833. else {
  29834. mesh = new Mesh(parsedMesh.name, scene);
  29835. }
  29836. mesh.id = parsedMesh.id;
  29837. if (BABYLON.Tags) {
  29838. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29839. }
  29840. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29841. if (parsedMesh.metadata !== undefined) {
  29842. mesh.metadata = parsedMesh.metadata;
  29843. }
  29844. if (parsedMesh.rotationQuaternion) {
  29845. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29846. }
  29847. else if (parsedMesh.rotation) {
  29848. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29849. }
  29850. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29851. if (parsedMesh.localMatrix) {
  29852. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29853. }
  29854. else if (parsedMesh.pivotMatrix) {
  29855. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29856. }
  29857. mesh.setEnabled(parsedMesh.isEnabled);
  29858. mesh.isVisible = parsedMesh.isVisible;
  29859. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29860. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29861. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29862. if (parsedMesh.applyFog !== undefined) {
  29863. mesh.applyFog = parsedMesh.applyFog;
  29864. }
  29865. if (parsedMesh.pickable !== undefined) {
  29866. mesh.isPickable = parsedMesh.pickable;
  29867. }
  29868. if (parsedMesh.alphaIndex !== undefined) {
  29869. mesh.alphaIndex = parsedMesh.alphaIndex;
  29870. }
  29871. mesh.receiveShadows = parsedMesh.receiveShadows;
  29872. mesh.billboardMode = parsedMesh.billboardMode;
  29873. if (parsedMesh.visibility !== undefined) {
  29874. mesh.visibility = parsedMesh.visibility;
  29875. }
  29876. mesh.checkCollisions = parsedMesh.checkCollisions;
  29877. if (parsedMesh.isBlocker !== undefined) {
  29878. mesh.isBlocker = parsedMesh.isBlocker;
  29879. }
  29880. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29881. // freezeWorldMatrix
  29882. if (parsedMesh.freezeWorldMatrix) {
  29883. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29884. }
  29885. // Parent
  29886. if (parsedMesh.parentId) {
  29887. mesh._waitingParentId = parsedMesh.parentId;
  29888. }
  29889. // Actions
  29890. if (parsedMesh.actions !== undefined) {
  29891. mesh._waitingActions = parsedMesh.actions;
  29892. }
  29893. // Overlay
  29894. if (parsedMesh.overlayAlpha !== undefined) {
  29895. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29896. }
  29897. if (parsedMesh.overlayColor !== undefined) {
  29898. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29899. }
  29900. if (parsedMesh.renderOverlay !== undefined) {
  29901. mesh.renderOverlay = parsedMesh.renderOverlay;
  29902. }
  29903. // Geometry
  29904. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29905. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29906. if (parsedMesh.delayLoadingFile) {
  29907. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29908. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29909. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29910. if (parsedMesh._binaryInfo) {
  29911. mesh._binaryInfo = parsedMesh._binaryInfo;
  29912. }
  29913. mesh._delayInfo = [];
  29914. if (parsedMesh.hasUVs) {
  29915. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29916. }
  29917. if (parsedMesh.hasUVs2) {
  29918. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29919. }
  29920. if (parsedMesh.hasUVs3) {
  29921. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29922. }
  29923. if (parsedMesh.hasUVs4) {
  29924. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29925. }
  29926. if (parsedMesh.hasUVs5) {
  29927. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29928. }
  29929. if (parsedMesh.hasUVs6) {
  29930. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29931. }
  29932. if (parsedMesh.hasColors) {
  29933. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29934. }
  29935. if (parsedMesh.hasMatricesIndices) {
  29936. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29937. }
  29938. if (parsedMesh.hasMatricesWeights) {
  29939. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29940. }
  29941. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29942. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29943. mesh._checkDelayState();
  29944. }
  29945. }
  29946. else {
  29947. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29948. }
  29949. // Material
  29950. if (parsedMesh.materialId) {
  29951. mesh.setMaterialByID(parsedMesh.materialId);
  29952. }
  29953. else {
  29954. mesh.material = null;
  29955. }
  29956. // Morph targets
  29957. if (parsedMesh.morphTargetManagerId > -1) {
  29958. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29959. }
  29960. // Skeleton
  29961. if (parsedMesh.skeletonId > -1) {
  29962. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29963. if (parsedMesh.numBoneInfluencers) {
  29964. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29965. }
  29966. }
  29967. // Animations
  29968. if (parsedMesh.animations) {
  29969. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29970. var parsedAnimation = parsedMesh.animations[animationIndex];
  29971. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29972. }
  29973. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29974. }
  29975. if (parsedMesh.autoAnimate) {
  29976. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29977. }
  29978. // Layer Mask
  29979. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29980. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29981. }
  29982. else {
  29983. mesh.layerMask = 0x0FFFFFFF;
  29984. }
  29985. // Physics
  29986. if (parsedMesh.physicsImpostor) {
  29987. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29988. mass: parsedMesh.physicsMass,
  29989. friction: parsedMesh.physicsFriction,
  29990. restitution: parsedMesh.physicsRestitution
  29991. }, scene);
  29992. }
  29993. // Instances
  29994. if (parsedMesh.instances) {
  29995. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29996. var parsedInstance = parsedMesh.instances[index];
  29997. var instance = mesh.createInstance(parsedInstance.name);
  29998. if (parsedInstance.id) {
  29999. instance.id = parsedInstance.id;
  30000. }
  30001. if (BABYLON.Tags) {
  30002. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  30003. }
  30004. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  30005. if (parsedInstance.parentId) {
  30006. instance._waitingParentId = parsedInstance.parentId;
  30007. }
  30008. if (parsedInstance.rotationQuaternion) {
  30009. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  30010. }
  30011. else if (parsedInstance.rotation) {
  30012. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  30013. }
  30014. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  30015. instance.checkCollisions = mesh.checkCollisions;
  30016. if (parsedMesh.animations) {
  30017. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  30018. parsedAnimation = parsedMesh.animations[animationIndex];
  30019. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30020. }
  30021. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  30022. }
  30023. }
  30024. }
  30025. return mesh;
  30026. };
  30027. /**
  30028. * Creates a ribbon mesh.
  30029. * Please consider using the same method from the MeshBuilder class instead.
  30030. * 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.
  30031. *
  30032. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  30033. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  30034. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  30035. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  30036. * 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.
  30037. * 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.
  30038. * 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
  30039. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30040. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30041. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30042. */
  30043. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  30044. if (closeArray === void 0) { closeArray = false; }
  30045. if (updatable === void 0) { updatable = false; }
  30046. return BABYLON.MeshBuilder.CreateRibbon(name, {
  30047. pathArray: pathArray,
  30048. closeArray: closeArray,
  30049. closePath: closePath,
  30050. offset: offset,
  30051. updatable: updatable,
  30052. sideOrientation: sideOrientation,
  30053. instance: instance
  30054. }, scene);
  30055. };
  30056. /**
  30057. * Creates a plane polygonal mesh. By default, this is a disc.
  30058. * Please consider using the same method from the MeshBuilder class instead.
  30059. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  30060. * 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.
  30061. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30062. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30063. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30064. */
  30065. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  30066. if (scene === void 0) { scene = null; }
  30067. var options = {
  30068. radius: radius,
  30069. tessellation: tessellation,
  30070. sideOrientation: sideOrientation,
  30071. updatable: updatable
  30072. };
  30073. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  30074. };
  30075. /**
  30076. * Creates a box mesh.
  30077. * Please consider using the same method from the MeshBuilder class instead.
  30078. * The parameter `size` sets the size (float) of each box side (default 1).
  30079. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30080. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30081. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30082. */
  30083. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  30084. if (scene === void 0) { scene = null; }
  30085. var options = {
  30086. size: size,
  30087. sideOrientation: sideOrientation,
  30088. updatable: updatable
  30089. };
  30090. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  30091. };
  30092. /**
  30093. * Creates a sphere mesh.
  30094. * Please consider using the same method from the MeshBuilder class instead.
  30095. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  30096. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  30097. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30098. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30099. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30100. */
  30101. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  30102. var options = {
  30103. segments: segments,
  30104. diameterX: diameter,
  30105. diameterY: diameter,
  30106. diameterZ: diameter,
  30107. sideOrientation: sideOrientation,
  30108. updatable: updatable
  30109. };
  30110. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  30111. };
  30112. /**
  30113. * Creates a cylinder or a cone mesh.
  30114. * Please consider using the same method from the MeshBuilder class instead.
  30115. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  30116. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  30117. * 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.
  30118. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  30119. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  30120. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30121. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30122. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30123. */
  30124. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  30125. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  30126. if (scene !== undefined) {
  30127. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  30128. updatable = scene;
  30129. }
  30130. scene = subdivisions;
  30131. subdivisions = 1;
  30132. }
  30133. var options = {
  30134. height: height,
  30135. diameterTop: diameterTop,
  30136. diameterBottom: diameterBottom,
  30137. tessellation: tessellation,
  30138. subdivisions: subdivisions,
  30139. sideOrientation: sideOrientation,
  30140. updatable: updatable
  30141. };
  30142. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  30143. };
  30144. // Torus (Code from SharpDX.org)
  30145. /**
  30146. * Creates a torus mesh.
  30147. * Please consider using the same method from the MeshBuilder class instead.
  30148. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  30149. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  30150. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  30151. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30152. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30153. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30154. */
  30155. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  30156. var options = {
  30157. diameter: diameter,
  30158. thickness: thickness,
  30159. tessellation: tessellation,
  30160. sideOrientation: sideOrientation,
  30161. updatable: updatable
  30162. };
  30163. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  30164. };
  30165. /**
  30166. * Creates a torus knot mesh.
  30167. * Please consider using the same method from the MeshBuilder class instead.
  30168. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  30169. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  30170. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  30171. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  30172. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30173. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30174. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30175. */
  30176. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  30177. var options = {
  30178. radius: radius,
  30179. tube: tube,
  30180. radialSegments: radialSegments,
  30181. tubularSegments: tubularSegments,
  30182. p: p,
  30183. q: q,
  30184. sideOrientation: sideOrientation,
  30185. updatable: updatable
  30186. };
  30187. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  30188. };
  30189. /**
  30190. * Creates a line mesh.
  30191. * Please consider using the same method from the MeshBuilder class instead.
  30192. * 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.
  30193. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30194. * The parameter `points` is an array successive Vector3.
  30195. * 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
  30196. * When updating an instance, remember that only point positions can change, not the number of points.
  30197. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30198. */
  30199. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  30200. if (scene === void 0) { scene = null; }
  30201. if (updatable === void 0) { updatable = false; }
  30202. if (instance === void 0) { instance = null; }
  30203. var options = {
  30204. points: points,
  30205. updatable: updatable,
  30206. instance: instance
  30207. };
  30208. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  30209. };
  30210. /**
  30211. * Creates a dashed line mesh.
  30212. * Please consider using the same method from the MeshBuilder class instead.
  30213. * 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.
  30214. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30215. * The parameter `points` is an array successive Vector3.
  30216. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  30217. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  30218. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  30219. * 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
  30220. * When updating an instance, remember that only point positions can change, not the number of points.
  30221. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30222. */
  30223. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  30224. if (scene === void 0) { scene = null; }
  30225. var options = {
  30226. points: points,
  30227. dashSize: dashSize,
  30228. gapSize: gapSize,
  30229. dashNb: dashNb,
  30230. updatable: updatable,
  30231. instance: instance
  30232. };
  30233. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  30234. };
  30235. /**
  30236. * Creates a polygon mesh.
  30237. * Please consider using the same method from the MeshBuilder class instead.
  30238. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  30239. * 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.
  30240. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30241. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30242. * Remember you can only change the shape positions, not their number when updating a polygon.
  30243. */
  30244. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  30245. var options = {
  30246. shape: shape,
  30247. holes: holes,
  30248. updatable: updatable,
  30249. sideOrientation: sideOrientation
  30250. };
  30251. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  30252. };
  30253. /**
  30254. * Creates an extruded polygon mesh, with depth in the Y direction.
  30255. * Please consider using the same method from the MeshBuilder class instead.
  30256. */
  30257. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  30258. var options = {
  30259. shape: shape,
  30260. holes: holes,
  30261. depth: depth,
  30262. updatable: updatable,
  30263. sideOrientation: sideOrientation
  30264. };
  30265. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  30266. };
  30267. /**
  30268. * Creates an extruded shape mesh.
  30269. * 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.
  30270. * Please consider using the same method from the MeshBuilder class instead.
  30271. *
  30272. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30273. * 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
  30274. * extruded along the Z axis.
  30275. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30276. * 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.
  30277. * The parameter `scale` (float, default 1) is the value to scale the shape.
  30278. * 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
  30279. * 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
  30280. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30281. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30282. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30283. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30284. */
  30285. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  30286. if (scene === void 0) { scene = null; }
  30287. var options = {
  30288. shape: shape,
  30289. path: path,
  30290. scale: scale,
  30291. rotation: rotation,
  30292. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30293. sideOrientation: sideOrientation,
  30294. instance: instance,
  30295. updatable: updatable
  30296. };
  30297. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  30298. };
  30299. /**
  30300. * Creates an custom extruded shape mesh.
  30301. * 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.
  30302. * Please consider using the same method from the MeshBuilder class instead.
  30303. *
  30304. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30305. * 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
  30306. * extruded along the Z axis.
  30307. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30308. * 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
  30309. * and the distance of this point from the begining of the path :
  30310. * ```javascript
  30311. * var rotationFunction = function(i, distance) {
  30312. * // do things
  30313. * return rotationValue; }
  30314. * ```
  30315. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  30316. * 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
  30317. * and the distance of this point from the begining of the path :
  30318. * ```javascript
  30319. * var scaleFunction = function(i, distance) {
  30320. * // do things
  30321. * return scaleValue;}
  30322. * ```
  30323. * It must returns a float value that will be the scale value applied to the shape on each path point.
  30324. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  30325. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  30326. * 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
  30327. * 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
  30328. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30329. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30330. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30331. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30332. */
  30333. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  30334. var options = {
  30335. shape: shape,
  30336. path: path,
  30337. scaleFunction: scaleFunction,
  30338. rotationFunction: rotationFunction,
  30339. ribbonCloseArray: ribbonCloseArray,
  30340. ribbonClosePath: ribbonClosePath,
  30341. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30342. sideOrientation: sideOrientation,
  30343. instance: instance,
  30344. updatable: updatable
  30345. };
  30346. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  30347. };
  30348. /**
  30349. * Creates lathe mesh.
  30350. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30351. * Please consider using the same method from the MeshBuilder class instead.
  30352. * 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
  30353. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30354. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30355. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30356. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30357. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30358. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30359. */
  30360. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30361. var options = {
  30362. shape: shape,
  30363. radius: radius,
  30364. tessellation: tessellation,
  30365. sideOrientation: sideOrientation,
  30366. updatable: updatable
  30367. };
  30368. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30369. };
  30370. /**
  30371. * Creates a plane mesh.
  30372. * Please consider using the same method from the MeshBuilder class instead.
  30373. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30374. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30375. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30376. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30377. */
  30378. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30379. var options = {
  30380. size: size,
  30381. width: size,
  30382. height: size,
  30383. sideOrientation: sideOrientation,
  30384. updatable: updatable
  30385. };
  30386. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30387. };
  30388. /**
  30389. * Creates a ground mesh.
  30390. * Please consider using the same method from the MeshBuilder class instead.
  30391. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30392. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  30393. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30394. */
  30395. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30396. var options = {
  30397. width: width,
  30398. height: height,
  30399. subdivisions: subdivisions,
  30400. updatable: updatable
  30401. };
  30402. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30403. };
  30404. /**
  30405. * Creates a tiled ground mesh.
  30406. * Please consider using the same method from the MeshBuilder class instead.
  30407. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30408. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30409. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30410. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30411. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30412. * numbers of subdivisions on the ground width and height of each tile.
  30413. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30414. */
  30415. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30416. var options = {
  30417. xmin: xmin,
  30418. zmin: zmin,
  30419. xmax: xmax,
  30420. zmax: zmax,
  30421. subdivisions: subdivisions,
  30422. precision: precision,
  30423. updatable: updatable
  30424. };
  30425. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30426. };
  30427. /**
  30428. * Creates a ground mesh from a height map.
  30429. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30430. * Please consider using the same method from the MeshBuilder class instead.
  30431. * The parameter `url` sets the URL of the height map image resource.
  30432. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30433. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30434. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30435. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30436. * 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).
  30437. * This function is passed the newly built mesh :
  30438. * ```javascript
  30439. * function(mesh) { // do things
  30440. * return; }
  30441. * ```
  30442. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30443. */
  30444. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30445. var options = {
  30446. width: width,
  30447. height: height,
  30448. subdivisions: subdivisions,
  30449. minHeight: minHeight,
  30450. maxHeight: maxHeight,
  30451. updatable: updatable,
  30452. onReady: onReady
  30453. };
  30454. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30455. };
  30456. /**
  30457. * Creates a tube mesh.
  30458. * 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.
  30459. * Please consider using the same method from the MeshBuilder class instead.
  30460. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30461. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30462. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30463. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30464. * 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.
  30465. * It must return a radius value (positive float) :
  30466. * ```javascript
  30467. * var radiusFunction = function(i, distance) {
  30468. * // do things
  30469. * return radius; }
  30470. * ```
  30471. * 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
  30472. * 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
  30473. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30474. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30475. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30476. */
  30477. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30478. var options = {
  30479. path: path,
  30480. radius: radius,
  30481. tessellation: tessellation,
  30482. radiusFunction: radiusFunction,
  30483. arc: 1,
  30484. cap: cap,
  30485. updatable: updatable,
  30486. sideOrientation: sideOrientation,
  30487. instance: instance
  30488. };
  30489. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30490. };
  30491. /**
  30492. * Creates a polyhedron mesh.
  30493. * Please consider using the same method from the MeshBuilder class instead.
  30494. * 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
  30495. * to choose the wanted type.
  30496. * The parameter `size` (positive float, default 1) sets the polygon size.
  30497. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30498. * 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`.
  30499. * 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
  30500. * 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)`).
  30501. * 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
  30502. * 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.
  30503. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30504. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30505. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30506. */
  30507. Mesh.CreatePolyhedron = function (name, options, scene) {
  30508. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30509. };
  30510. /**
  30511. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30512. * Please consider using the same method from the MeshBuilder class instead.
  30513. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30514. * 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`).
  30515. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30516. * 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.
  30517. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30518. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30519. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30520. */
  30521. Mesh.CreateIcoSphere = function (name, options, scene) {
  30522. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30523. };
  30524. /**
  30525. * Creates a decal mesh.
  30526. * Please consider using the same method from the MeshBuilder class instead.
  30527. * 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.
  30528. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30529. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30530. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30531. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30532. */
  30533. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30534. var options = {
  30535. position: position,
  30536. normal: normal,
  30537. size: size,
  30538. angle: angle
  30539. };
  30540. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30541. };
  30542. // Skeletons
  30543. /**
  30544. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30545. */
  30546. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30547. if (!this._sourcePositions) {
  30548. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30549. if (!source) {
  30550. return this._sourcePositions;
  30551. }
  30552. this._sourcePositions = new Float32Array(source);
  30553. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30554. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30555. }
  30556. }
  30557. return this._sourcePositions;
  30558. };
  30559. /**
  30560. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30561. */
  30562. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30563. if (!this._sourceNormals) {
  30564. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30565. if (!source) {
  30566. return this._sourceNormals;
  30567. }
  30568. this._sourceNormals = new Float32Array(source);
  30569. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30570. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30571. }
  30572. }
  30573. return this._sourceNormals;
  30574. };
  30575. /**
  30576. * Updates the vertex buffer by applying transformation from the bones.
  30577. * Returns the Mesh.
  30578. *
  30579. * @param {skeleton} skeleton to apply
  30580. */
  30581. Mesh.prototype.applySkeleton = function (skeleton) {
  30582. if (!this.geometry) {
  30583. return this;
  30584. }
  30585. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30586. return this;
  30587. }
  30588. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30589. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30590. return this;
  30591. }
  30592. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30593. return this;
  30594. }
  30595. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30596. return this;
  30597. }
  30598. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30599. return this;
  30600. }
  30601. if (!this._sourcePositions) {
  30602. var submeshes = this.subMeshes.slice();
  30603. this.setPositionsForCPUSkinning();
  30604. this.subMeshes = submeshes;
  30605. }
  30606. if (!this._sourceNormals) {
  30607. this.setNormalsForCPUSkinning();
  30608. }
  30609. // positionsData checks for not being Float32Array will only pass at most once
  30610. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30611. if (!positionsData) {
  30612. return this;
  30613. }
  30614. if (!(positionsData instanceof Float32Array)) {
  30615. positionsData = new Float32Array(positionsData);
  30616. }
  30617. // normalsData checks for not being Float32Array will only pass at most once
  30618. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30619. if (!normalsData) {
  30620. return this;
  30621. }
  30622. if (!(normalsData instanceof Float32Array)) {
  30623. normalsData = new Float32Array(normalsData);
  30624. }
  30625. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30626. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30627. if (!matricesWeightsData || !matricesIndicesData) {
  30628. return this;
  30629. }
  30630. var needExtras = this.numBoneInfluencers > 4;
  30631. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30632. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30633. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30634. var tempVector3 = BABYLON.Vector3.Zero();
  30635. var finalMatrix = new BABYLON.Matrix();
  30636. var tempMatrix = new BABYLON.Matrix();
  30637. var matWeightIdx = 0;
  30638. var inf;
  30639. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30640. var weight;
  30641. for (inf = 0; inf < 4; inf++) {
  30642. weight = matricesWeightsData[matWeightIdx + inf];
  30643. if (weight > 0) {
  30644. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30645. finalMatrix.addToSelf(tempMatrix);
  30646. }
  30647. else
  30648. break;
  30649. }
  30650. if (needExtras) {
  30651. for (inf = 0; inf < 4; inf++) {
  30652. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30653. if (weight > 0) {
  30654. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30655. finalMatrix.addToSelf(tempMatrix);
  30656. }
  30657. else
  30658. break;
  30659. }
  30660. }
  30661. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30662. tempVector3.toArray(positionsData, index);
  30663. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30664. tempVector3.toArray(normalsData, index);
  30665. finalMatrix.reset();
  30666. }
  30667. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30668. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30669. return this;
  30670. };
  30671. // Tools
  30672. /**
  30673. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30674. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30675. */
  30676. Mesh.MinMax = function (meshes) {
  30677. var minVector = null;
  30678. var maxVector = null;
  30679. meshes.forEach(function (mesh, index, array) {
  30680. var boundingInfo = mesh.getBoundingInfo();
  30681. var boundingBox = boundingInfo.boundingBox;
  30682. if (!minVector || !maxVector) {
  30683. minVector = boundingBox.minimumWorld;
  30684. maxVector = boundingBox.maximumWorld;
  30685. }
  30686. else {
  30687. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30688. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30689. }
  30690. });
  30691. if (!minVector || !maxVector) {
  30692. return {
  30693. min: BABYLON.Vector3.Zero(),
  30694. max: BABYLON.Vector3.Zero()
  30695. };
  30696. }
  30697. return {
  30698. min: minVector,
  30699. max: maxVector
  30700. };
  30701. };
  30702. /**
  30703. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30704. */
  30705. Mesh.Center = function (meshesOrMinMaxVector) {
  30706. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30707. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30708. };
  30709. /**
  30710. * Merge the array of meshes into a single mesh for performance reasons.
  30711. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30712. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30713. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30714. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30715. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30716. */
  30717. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30718. if (disposeSource === void 0) { disposeSource = true; }
  30719. var index;
  30720. if (!allow32BitsIndices) {
  30721. var totalVertices = 0;
  30722. // Counting vertices
  30723. for (index = 0; index < meshes.length; index++) {
  30724. if (meshes[index]) {
  30725. totalVertices += meshes[index].getTotalVertices();
  30726. if (totalVertices > 65536) {
  30727. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30728. return null;
  30729. }
  30730. }
  30731. }
  30732. }
  30733. // Merge
  30734. var vertexData = null;
  30735. var otherVertexData;
  30736. var indiceArray = new Array();
  30737. var source = null;
  30738. for (index = 0; index < meshes.length; index++) {
  30739. if (meshes[index]) {
  30740. meshes[index].computeWorldMatrix(true);
  30741. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30742. otherVertexData.transform(meshes[index].getWorldMatrix());
  30743. if (vertexData) {
  30744. vertexData.merge(otherVertexData);
  30745. }
  30746. else {
  30747. vertexData = otherVertexData;
  30748. source = meshes[index];
  30749. }
  30750. if (subdivideWithSubMeshes) {
  30751. indiceArray.push(meshes[index].getTotalIndices());
  30752. }
  30753. }
  30754. }
  30755. source = source;
  30756. if (!meshSubclass) {
  30757. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30758. }
  30759. vertexData.applyToMesh(meshSubclass);
  30760. // Setting properties
  30761. meshSubclass.material = source.material;
  30762. meshSubclass.checkCollisions = source.checkCollisions;
  30763. // Cleaning
  30764. if (disposeSource) {
  30765. for (index = 0; index < meshes.length; index++) {
  30766. if (meshes[index]) {
  30767. meshes[index].dispose();
  30768. }
  30769. }
  30770. }
  30771. // Subdivide
  30772. if (subdivideWithSubMeshes) {
  30773. //-- Suppresions du submesh global
  30774. meshSubclass.releaseSubMeshes();
  30775. index = 0;
  30776. var offset = 0;
  30777. //-- aplique la subdivision en fonction du tableau d'indices
  30778. while (index < indiceArray.length) {
  30779. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30780. offset += indiceArray[index];
  30781. index++;
  30782. }
  30783. }
  30784. return meshSubclass;
  30785. };
  30786. // Consts
  30787. Mesh._FRONTSIDE = 0;
  30788. Mesh._BACKSIDE = 1;
  30789. Mesh._DOUBLESIDE = 2;
  30790. Mesh._DEFAULTSIDE = 0;
  30791. Mesh._NO_CAP = 0;
  30792. Mesh._CAP_START = 1;
  30793. Mesh._CAP_END = 2;
  30794. Mesh._CAP_ALL = 3;
  30795. return Mesh;
  30796. }(BABYLON.AbstractMesh));
  30797. BABYLON.Mesh = Mesh;
  30798. })(BABYLON || (BABYLON = {}));
  30799. //# sourceMappingURL=babylon.mesh.js.map
  30800. "use strict";
  30801. var BABYLON;
  30802. (function (BABYLON) {
  30803. var BaseSubMesh = /** @class */ (function () {
  30804. function BaseSubMesh() {
  30805. }
  30806. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30807. get: function () {
  30808. return this._materialEffect;
  30809. },
  30810. enumerable: true,
  30811. configurable: true
  30812. });
  30813. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30814. if (defines === void 0) { defines = null; }
  30815. if (this._materialEffect === effect) {
  30816. if (!effect) {
  30817. this._materialDefines = null;
  30818. }
  30819. return;
  30820. }
  30821. this._materialDefines = defines;
  30822. this._materialEffect = effect;
  30823. };
  30824. return BaseSubMesh;
  30825. }());
  30826. BABYLON.BaseSubMesh = BaseSubMesh;
  30827. var SubMesh = /** @class */ (function (_super) {
  30828. __extends(SubMesh, _super);
  30829. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30830. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30831. var _this = _super.call(this) || this;
  30832. _this.materialIndex = materialIndex;
  30833. _this.verticesStart = verticesStart;
  30834. _this.verticesCount = verticesCount;
  30835. _this.indexStart = indexStart;
  30836. _this.indexCount = indexCount;
  30837. _this._renderId = 0;
  30838. _this._mesh = mesh;
  30839. _this._renderingMesh = renderingMesh || mesh;
  30840. mesh.subMeshes.push(_this);
  30841. _this._trianglePlanes = [];
  30842. _this._id = mesh.subMeshes.length - 1;
  30843. if (createBoundingBox) {
  30844. _this.refreshBoundingInfo();
  30845. mesh.computeWorldMatrix(true);
  30846. }
  30847. return _this;
  30848. }
  30849. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30850. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30851. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30852. };
  30853. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30854. get: function () {
  30855. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30856. },
  30857. enumerable: true,
  30858. configurable: true
  30859. });
  30860. /**
  30861. * Returns the submesh BoudingInfo object.
  30862. */
  30863. SubMesh.prototype.getBoundingInfo = function () {
  30864. if (this.IsGlobal) {
  30865. return this._mesh.getBoundingInfo();
  30866. }
  30867. return this._boundingInfo;
  30868. };
  30869. /**
  30870. * Sets the submesh BoundingInfo.
  30871. * Return the SubMesh.
  30872. */
  30873. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30874. this._boundingInfo = boundingInfo;
  30875. return this;
  30876. };
  30877. /**
  30878. * Returns the mesh of the current submesh.
  30879. */
  30880. SubMesh.prototype.getMesh = function () {
  30881. return this._mesh;
  30882. };
  30883. /**
  30884. * Returns the rendering mesh of the submesh.
  30885. */
  30886. SubMesh.prototype.getRenderingMesh = function () {
  30887. return this._renderingMesh;
  30888. };
  30889. /**
  30890. * Returns the submesh material.
  30891. */
  30892. SubMesh.prototype.getMaterial = function () {
  30893. var rootMaterial = this._renderingMesh.material;
  30894. if (rootMaterial === null || rootMaterial === undefined) {
  30895. return this._mesh.getScene().defaultMaterial;
  30896. }
  30897. else if (rootMaterial.getSubMaterial) {
  30898. var multiMaterial = rootMaterial;
  30899. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30900. if (this._currentMaterial !== effectiveMaterial) {
  30901. this._currentMaterial = effectiveMaterial;
  30902. this._materialDefines = null;
  30903. }
  30904. return effectiveMaterial;
  30905. }
  30906. return rootMaterial;
  30907. };
  30908. // Methods
  30909. /**
  30910. * Sets a new updated BoundingInfo object to the submesh.
  30911. * Returns the SubMesh.
  30912. */
  30913. SubMesh.prototype.refreshBoundingInfo = function () {
  30914. this._lastColliderWorldVertices = null;
  30915. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30916. return this;
  30917. }
  30918. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30919. if (!data) {
  30920. this._boundingInfo = this._mesh.getBoundingInfo();
  30921. return this;
  30922. }
  30923. var indices = this._renderingMesh.getIndices();
  30924. var extend;
  30925. //is this the only submesh?
  30926. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30927. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30928. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30929. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30930. }
  30931. else {
  30932. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30933. }
  30934. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30935. return this;
  30936. };
  30937. SubMesh.prototype._checkCollision = function (collider) {
  30938. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30939. return boundingInfo._checkCollision(collider);
  30940. };
  30941. /**
  30942. * Updates the submesh BoundingInfo.
  30943. * Returns the Submesh.
  30944. */
  30945. SubMesh.prototype.updateBoundingInfo = function (world) {
  30946. var boundingInfo = this.getBoundingInfo();
  30947. if (!boundingInfo) {
  30948. this.refreshBoundingInfo();
  30949. boundingInfo = this.getBoundingInfo();
  30950. }
  30951. boundingInfo.update(world);
  30952. return this;
  30953. };
  30954. /**
  30955. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30956. * Boolean returned.
  30957. */
  30958. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30959. var boundingInfo = this.getBoundingInfo();
  30960. if (!boundingInfo) {
  30961. return false;
  30962. }
  30963. return boundingInfo.isInFrustum(frustumPlanes);
  30964. };
  30965. /**
  30966. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30967. * Boolean returned.
  30968. */
  30969. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30970. var boundingInfo = this.getBoundingInfo();
  30971. if (!boundingInfo) {
  30972. return false;
  30973. }
  30974. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30975. };
  30976. /**
  30977. * Renders the submesh.
  30978. * Returns it.
  30979. */
  30980. SubMesh.prototype.render = function (enableAlphaMode) {
  30981. this._renderingMesh.render(this, enableAlphaMode);
  30982. return this;
  30983. };
  30984. /**
  30985. * Returns a new Index Buffer.
  30986. * Type returned : WebGLBuffer.
  30987. */
  30988. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30989. if (!this._linesIndexBuffer) {
  30990. var linesIndices = [];
  30991. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30992. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30993. }
  30994. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30995. this.linesIndexCount = linesIndices.length;
  30996. }
  30997. return this._linesIndexBuffer;
  30998. };
  30999. /**
  31000. * True is the passed Ray intersects the submesh bounding box.
  31001. * Boolean returned.
  31002. */
  31003. SubMesh.prototype.canIntersects = function (ray) {
  31004. var boundingInfo = this.getBoundingInfo();
  31005. if (!boundingInfo) {
  31006. return false;
  31007. }
  31008. return ray.intersectsBox(boundingInfo.boundingBox);
  31009. };
  31010. /**
  31011. * Returns an object IntersectionInfo.
  31012. */
  31013. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  31014. var intersectInfo = null;
  31015. var material = this.getMaterial();
  31016. if (!material) {
  31017. return null;
  31018. }
  31019. switch (material.fillMode) {
  31020. case BABYLON.Material.PointListDrawMode:
  31021. case BABYLON.Material.LineListDrawMode:
  31022. case BABYLON.Material.LineLoopDrawMode:
  31023. case BABYLON.Material.LineStripDrawMode:
  31024. case BABYLON.Material.TriangleFanDrawMode:
  31025. case BABYLON.Material.TriangleStripDrawMode:
  31026. return null;
  31027. }
  31028. // LineMesh first as it's also a Mesh...
  31029. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  31030. var lineMesh = this._mesh;
  31031. // Line test
  31032. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  31033. var p0 = positions[indices[index]];
  31034. var p1 = positions[indices[index + 1]];
  31035. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  31036. if (length < 0) {
  31037. continue;
  31038. }
  31039. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  31040. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  31041. if (fastCheck) {
  31042. break;
  31043. }
  31044. }
  31045. }
  31046. }
  31047. else {
  31048. // Triangles test
  31049. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31050. var p0 = positions[indices[index]];
  31051. var p1 = positions[indices[index + 1]];
  31052. var p2 = positions[indices[index + 2]];
  31053. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  31054. if (currentIntersectInfo) {
  31055. if (currentIntersectInfo.distance < 0) {
  31056. continue;
  31057. }
  31058. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  31059. intersectInfo = currentIntersectInfo;
  31060. intersectInfo.faceId = index / 3;
  31061. if (fastCheck) {
  31062. break;
  31063. }
  31064. }
  31065. }
  31066. }
  31067. }
  31068. return intersectInfo;
  31069. };
  31070. SubMesh.prototype._rebuild = function () {
  31071. if (this._linesIndexBuffer) {
  31072. this._linesIndexBuffer = null;
  31073. }
  31074. };
  31075. // Clone
  31076. /**
  31077. * Creates a new Submesh from the passed Mesh.
  31078. */
  31079. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  31080. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  31081. if (!this.IsGlobal) {
  31082. var boundingInfo = this.getBoundingInfo();
  31083. if (!boundingInfo) {
  31084. return result;
  31085. }
  31086. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  31087. }
  31088. return result;
  31089. };
  31090. // Dispose
  31091. /**
  31092. * Disposes the Submesh.
  31093. * Returns nothing.
  31094. */
  31095. SubMesh.prototype.dispose = function () {
  31096. if (this._linesIndexBuffer) {
  31097. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  31098. this._linesIndexBuffer = null;
  31099. }
  31100. // Remove from mesh
  31101. var index = this._mesh.subMeshes.indexOf(this);
  31102. this._mesh.subMeshes.splice(index, 1);
  31103. };
  31104. // Statics
  31105. /**
  31106. * Creates a new Submesh from the passed parameters :
  31107. * - materialIndex (integer) : the index of the main mesh material.
  31108. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  31109. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  31110. * - mesh (Mesh) : the main mesh to create the submesh from.
  31111. * - renderingMesh (optional Mesh) : rendering mesh.
  31112. */
  31113. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  31114. var minVertexIndex = Number.MAX_VALUE;
  31115. var maxVertexIndex = -Number.MAX_VALUE;
  31116. renderingMesh = (renderingMesh || mesh);
  31117. var indices = renderingMesh.getIndices();
  31118. for (var index = startIndex; index < startIndex + indexCount; index++) {
  31119. var vertexIndex = indices[index];
  31120. if (vertexIndex < minVertexIndex)
  31121. minVertexIndex = vertexIndex;
  31122. if (vertexIndex > maxVertexIndex)
  31123. maxVertexIndex = vertexIndex;
  31124. }
  31125. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  31126. };
  31127. return SubMesh;
  31128. }(BaseSubMesh));
  31129. BABYLON.SubMesh = SubMesh;
  31130. })(BABYLON || (BABYLON = {}));
  31131. //# sourceMappingURL=babylon.subMesh.js.map
  31132. "use strict";
  31133. var __assign = (this && this.__assign) || Object.assign || function(t) {
  31134. for (var s, i = 1, n = arguments.length; i < n; i++) {
  31135. s = arguments[i];
  31136. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  31137. t[p] = s[p];
  31138. }
  31139. return t;
  31140. };
  31141. var BABYLON;
  31142. (function (BABYLON) {
  31143. /**
  31144. * Manages the defines for the Material.
  31145. */
  31146. var MaterialDefines = /** @class */ (function () {
  31147. function MaterialDefines() {
  31148. this._isDirty = true;
  31149. this._areLightsDirty = true;
  31150. this._areAttributesDirty = true;
  31151. this._areTexturesDirty = true;
  31152. this._areFresnelDirty = true;
  31153. this._areMiscDirty = true;
  31154. this._areImageProcessingDirty = true;
  31155. this._normals = false;
  31156. this._uvs = false;
  31157. this._needNormals = false;
  31158. this._needUVs = false;
  31159. }
  31160. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  31161. /**
  31162. * Specifies if the material needs to be re-calculated.
  31163. */
  31164. get: function () {
  31165. return this._isDirty;
  31166. },
  31167. enumerable: true,
  31168. configurable: true
  31169. });
  31170. /**
  31171. * Marks the material to indicate that it has been re-calculated.
  31172. */
  31173. MaterialDefines.prototype.markAsProcessed = function () {
  31174. this._isDirty = false;
  31175. this._areAttributesDirty = false;
  31176. this._areTexturesDirty = false;
  31177. this._areFresnelDirty = false;
  31178. this._areLightsDirty = false;
  31179. this._areMiscDirty = false;
  31180. this._areImageProcessingDirty = false;
  31181. };
  31182. /**
  31183. * Marks the material to indicate that it needs to be re-calculated.
  31184. */
  31185. MaterialDefines.prototype.markAsUnprocessed = function () {
  31186. this._isDirty = true;
  31187. };
  31188. /**
  31189. * Marks the material to indicate all of its defines need to be re-calculated.
  31190. */
  31191. MaterialDefines.prototype.markAllAsDirty = function () {
  31192. this._areTexturesDirty = true;
  31193. this._areAttributesDirty = true;
  31194. this._areLightsDirty = true;
  31195. this._areFresnelDirty = true;
  31196. this._areMiscDirty = true;
  31197. this._areImageProcessingDirty = true;
  31198. this._isDirty = true;
  31199. };
  31200. /**
  31201. * Marks the material to indicate that image processing needs to be re-calculated.
  31202. */
  31203. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  31204. this._areImageProcessingDirty = true;
  31205. this._isDirty = true;
  31206. };
  31207. /**
  31208. * Marks the material to indicate the lights need to be re-calculated.
  31209. */
  31210. MaterialDefines.prototype.markAsLightDirty = function () {
  31211. this._areLightsDirty = true;
  31212. this._isDirty = true;
  31213. };
  31214. /**
  31215. * Marks the attribute state as changed.
  31216. */
  31217. MaterialDefines.prototype.markAsAttributesDirty = function () {
  31218. this._areAttributesDirty = true;
  31219. this._isDirty = true;
  31220. };
  31221. /**
  31222. * Marks the texture state as changed.
  31223. */
  31224. MaterialDefines.prototype.markAsTexturesDirty = function () {
  31225. this._areTexturesDirty = true;
  31226. this._isDirty = true;
  31227. };
  31228. /**
  31229. * Marks the fresnel state as changed.
  31230. */
  31231. MaterialDefines.prototype.markAsFresnelDirty = function () {
  31232. this._areFresnelDirty = true;
  31233. this._isDirty = true;
  31234. };
  31235. /**
  31236. * Marks the misc state as changed.
  31237. */
  31238. MaterialDefines.prototype.markAsMiscDirty = function () {
  31239. this._areMiscDirty = true;
  31240. this._isDirty = true;
  31241. };
  31242. /**
  31243. * Rebuilds the material defines.
  31244. */
  31245. MaterialDefines.prototype.rebuild = function () {
  31246. if (this._keys) {
  31247. delete this._keys;
  31248. }
  31249. this._keys = [];
  31250. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  31251. var key = _a[_i];
  31252. if (key[0] === "_") {
  31253. continue;
  31254. }
  31255. this._keys.push(key);
  31256. }
  31257. };
  31258. /**
  31259. * Specifies if two material defines are equal.
  31260. * @param other - A material define instance to compare to.
  31261. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  31262. */
  31263. MaterialDefines.prototype.isEqual = function (other) {
  31264. if (this._keys.length !== other._keys.length) {
  31265. return false;
  31266. }
  31267. for (var index = 0; index < this._keys.length; index++) {
  31268. var prop = this._keys[index];
  31269. if (this[prop] !== other[prop]) {
  31270. return false;
  31271. }
  31272. }
  31273. return true;
  31274. };
  31275. /**
  31276. * Clones this instance's defines to another instance.
  31277. * @param other - material defines to clone values to.
  31278. */
  31279. MaterialDefines.prototype.cloneTo = function (other) {
  31280. if (this._keys.length !== other._keys.length) {
  31281. other._keys = this._keys.slice(0);
  31282. }
  31283. for (var index = 0; index < this._keys.length; index++) {
  31284. var prop = this._keys[index];
  31285. other[prop] = this[prop];
  31286. }
  31287. };
  31288. /**
  31289. * Resets the material define values.
  31290. */
  31291. MaterialDefines.prototype.reset = function () {
  31292. for (var index = 0; index < this._keys.length; index++) {
  31293. var prop = this._keys[index];
  31294. var type = typeof this[prop];
  31295. switch (type) {
  31296. case "number":
  31297. this[prop] = 0;
  31298. break;
  31299. case "string":
  31300. this[prop] = "";
  31301. break;
  31302. default:
  31303. this[prop] = false;
  31304. break;
  31305. }
  31306. }
  31307. };
  31308. /**
  31309. * Converts the material define values to a string.
  31310. * @returns - String of material define information.
  31311. */
  31312. MaterialDefines.prototype.toString = function () {
  31313. var result = "";
  31314. for (var index = 0; index < this._keys.length; index++) {
  31315. var prop = this._keys[index];
  31316. var value = this[prop];
  31317. var type = typeof value;
  31318. switch (type) {
  31319. case "number":
  31320. case "string":
  31321. result += "#define " + prop + " " + value + "\n";
  31322. break;
  31323. default:
  31324. if (value) {
  31325. result += "#define " + prop + "\n";
  31326. }
  31327. break;
  31328. }
  31329. }
  31330. return result;
  31331. };
  31332. return MaterialDefines;
  31333. }());
  31334. BABYLON.MaterialDefines = MaterialDefines;
  31335. /**
  31336. * This offers the main features of a material in BJS.
  31337. */
  31338. var Material = /** @class */ (function () {
  31339. /**
  31340. * Creates a material instance.
  31341. * @param name - The name of the material.
  31342. * @param scene - The BJS scene to reference.
  31343. * @param doNotAdd - Specifies if the material should be added to the scene.
  31344. */
  31345. function Material(name, scene, doNotAdd) {
  31346. /**
  31347. * Specifies if the ready state should be checked on each call.
  31348. */
  31349. this.checkReadyOnEveryCall = false;
  31350. /**
  31351. * Specifies if the ready state should be checked once.
  31352. */
  31353. this.checkReadyOnlyOnce = false;
  31354. /**
  31355. * The state of the material.
  31356. */
  31357. this.state = "";
  31358. /**
  31359. * The alpha value of the material.
  31360. */
  31361. this._alpha = 1.0;
  31362. /**
  31363. * Specifies if back face culling is enabled.
  31364. */
  31365. this._backFaceCulling = true;
  31366. /**
  31367. * Specifies if the material should be serialized.
  31368. */
  31369. this.doNotSerialize = false;
  31370. /**
  31371. * Specifies if the effect should be stored on sub meshes.
  31372. */
  31373. this.storeEffectOnSubMeshes = false;
  31374. /**
  31375. * An event triggered when the material is disposed.
  31376. * @type {BABYLON.Observable}
  31377. */
  31378. this.onDisposeObservable = new BABYLON.Observable();
  31379. /**
  31380. * An event triggered when the material is bound.
  31381. * @type {BABYLON.Observable}
  31382. */
  31383. this.onBindObservable = new BABYLON.Observable();
  31384. /**
  31385. * An event triggered when the material is unbound.
  31386. * @type {BABYLON.Observable}
  31387. */
  31388. this.onUnBindObservable = new BABYLON.Observable();
  31389. /**
  31390. * Stores the value of the alpha mode.
  31391. */
  31392. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31393. /**
  31394. * Stores the state of the need depth pre-pass value.
  31395. */
  31396. this._needDepthPrePass = false;
  31397. /**
  31398. * Specifies if depth writing should be disabled.
  31399. */
  31400. this.disableDepthWrite = false;
  31401. /**
  31402. * Specifies if depth writing should be forced.
  31403. */
  31404. this.forceDepthWrite = false;
  31405. /**
  31406. * Specifies if there should be a separate pass for culling.
  31407. */
  31408. this.separateCullingPass = false;
  31409. /**
  31410. * Stores the state specifing if fog should be enabled.
  31411. */
  31412. this._fogEnabled = true;
  31413. /**
  31414. * Stores the size of points.
  31415. */
  31416. this.pointSize = 1.0;
  31417. /**
  31418. * Stores the z offset value.
  31419. */
  31420. this.zOffset = 0;
  31421. /**
  31422. * Specifies if the material was previously ready.
  31423. */
  31424. this._wasPreviouslyReady = false;
  31425. /**
  31426. * Stores the fill mode state.
  31427. */
  31428. this._fillMode = Material.TriangleFillMode;
  31429. this.name = name;
  31430. this.id = name || BABYLON.Tools.RandomId();
  31431. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31432. if (this._scene.useRightHandedSystem) {
  31433. this.sideOrientation = Material.ClockWiseSideOrientation;
  31434. }
  31435. else {
  31436. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31437. }
  31438. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31439. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31440. if (!doNotAdd) {
  31441. this._scene.materials.push(this);
  31442. }
  31443. }
  31444. Object.defineProperty(Material, "TriangleFillMode", {
  31445. /**
  31446. * Returns the triangle fill mode.
  31447. */
  31448. get: function () {
  31449. return Material._TriangleFillMode;
  31450. },
  31451. enumerable: true,
  31452. configurable: true
  31453. });
  31454. Object.defineProperty(Material, "WireFrameFillMode", {
  31455. /**
  31456. * Returns the wireframe mode.
  31457. */
  31458. get: function () {
  31459. return Material._WireFrameFillMode;
  31460. },
  31461. enumerable: true,
  31462. configurable: true
  31463. });
  31464. Object.defineProperty(Material, "PointFillMode", {
  31465. /**
  31466. * Returns the point fill mode.
  31467. */
  31468. get: function () {
  31469. return Material._PointFillMode;
  31470. },
  31471. enumerable: true,
  31472. configurable: true
  31473. });
  31474. Object.defineProperty(Material, "PointListDrawMode", {
  31475. /**
  31476. * Returns the point list draw mode.
  31477. */
  31478. get: function () {
  31479. return Material._PointListDrawMode;
  31480. },
  31481. enumerable: true,
  31482. configurable: true
  31483. });
  31484. Object.defineProperty(Material, "LineListDrawMode", {
  31485. /**
  31486. * Returns the line list draw mode.
  31487. */
  31488. get: function () {
  31489. return Material._LineListDrawMode;
  31490. },
  31491. enumerable: true,
  31492. configurable: true
  31493. });
  31494. Object.defineProperty(Material, "LineLoopDrawMode", {
  31495. /**
  31496. * Returns the line loop draw mode.
  31497. */
  31498. get: function () {
  31499. return Material._LineLoopDrawMode;
  31500. },
  31501. enumerable: true,
  31502. configurable: true
  31503. });
  31504. Object.defineProperty(Material, "LineStripDrawMode", {
  31505. /**
  31506. * Returns the line strip draw mode.
  31507. */
  31508. get: function () {
  31509. return Material._LineStripDrawMode;
  31510. },
  31511. enumerable: true,
  31512. configurable: true
  31513. });
  31514. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31515. /**
  31516. * Returns the triangle strip draw mode.
  31517. */
  31518. get: function () {
  31519. return Material._TriangleStripDrawMode;
  31520. },
  31521. enumerable: true,
  31522. configurable: true
  31523. });
  31524. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31525. /**
  31526. * Returns the triangle fan draw mode.
  31527. */
  31528. get: function () {
  31529. return Material._TriangleFanDrawMode;
  31530. },
  31531. enumerable: true,
  31532. configurable: true
  31533. });
  31534. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31535. /**
  31536. * Returns the clock-wise side orientation.
  31537. */
  31538. get: function () {
  31539. return Material._ClockWiseSideOrientation;
  31540. },
  31541. enumerable: true,
  31542. configurable: true
  31543. });
  31544. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31545. /**
  31546. * Returns the counter clock-wise side orientation.
  31547. */
  31548. get: function () {
  31549. return Material._CounterClockWiseSideOrientation;
  31550. },
  31551. enumerable: true,
  31552. configurable: true
  31553. });
  31554. Object.defineProperty(Material, "TextureDirtyFlag", {
  31555. /**
  31556. * Returns the dirty texture flag value.
  31557. */
  31558. get: function () {
  31559. return Material._TextureDirtyFlag;
  31560. },
  31561. enumerable: true,
  31562. configurable: true
  31563. });
  31564. Object.defineProperty(Material, "LightDirtyFlag", {
  31565. /**
  31566. * Returns the dirty light flag value.
  31567. */
  31568. get: function () {
  31569. return Material._LightDirtyFlag;
  31570. },
  31571. enumerable: true,
  31572. configurable: true
  31573. });
  31574. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31575. /**
  31576. * Returns the dirty fresnel flag value.
  31577. */
  31578. get: function () {
  31579. return Material._FresnelDirtyFlag;
  31580. },
  31581. enumerable: true,
  31582. configurable: true
  31583. });
  31584. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31585. /**
  31586. * Returns the dirty attributes flag value.
  31587. */
  31588. get: function () {
  31589. return Material._AttributesDirtyFlag;
  31590. },
  31591. enumerable: true,
  31592. configurable: true
  31593. });
  31594. Object.defineProperty(Material, "MiscDirtyFlag", {
  31595. /**
  31596. * Returns the dirty misc flag value.
  31597. */
  31598. get: function () {
  31599. return Material._MiscDirtyFlag;
  31600. },
  31601. enumerable: true,
  31602. configurable: true
  31603. });
  31604. Object.defineProperty(Material.prototype, "alpha", {
  31605. /**
  31606. * Gets the alpha value of the material.
  31607. */
  31608. get: function () {
  31609. return this._alpha;
  31610. },
  31611. /**
  31612. * Sets the alpha value of the material.
  31613. */
  31614. set: function (value) {
  31615. if (this._alpha === value) {
  31616. return;
  31617. }
  31618. this._alpha = value;
  31619. this.markAsDirty(Material.MiscDirtyFlag);
  31620. },
  31621. enumerable: true,
  31622. configurable: true
  31623. });
  31624. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31625. /**
  31626. * Gets the back-face culling state.
  31627. */
  31628. get: function () {
  31629. return this._backFaceCulling;
  31630. },
  31631. /**
  31632. * Sets the back-face culling state.
  31633. */
  31634. set: function (value) {
  31635. if (this._backFaceCulling === value) {
  31636. return;
  31637. }
  31638. this._backFaceCulling = value;
  31639. this.markAsDirty(Material.TextureDirtyFlag);
  31640. },
  31641. enumerable: true,
  31642. configurable: true
  31643. });
  31644. Object.defineProperty(Material.prototype, "onDispose", {
  31645. /**
  31646. * Called during a dispose event.
  31647. */
  31648. set: function (callback) {
  31649. if (this._onDisposeObserver) {
  31650. this.onDisposeObservable.remove(this._onDisposeObserver);
  31651. }
  31652. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31653. },
  31654. enumerable: true,
  31655. configurable: true
  31656. });
  31657. Object.defineProperty(Material.prototype, "onBind", {
  31658. /**
  31659. * Called during a bind event.
  31660. */
  31661. set: function (callback) {
  31662. if (this._onBindObserver) {
  31663. this.onBindObservable.remove(this._onBindObserver);
  31664. }
  31665. this._onBindObserver = this.onBindObservable.add(callback);
  31666. },
  31667. enumerable: true,
  31668. configurable: true
  31669. });
  31670. Object.defineProperty(Material.prototype, "alphaMode", {
  31671. /**
  31672. * Gets the value of the alpha mode.
  31673. */
  31674. get: function () {
  31675. return this._alphaMode;
  31676. },
  31677. /**
  31678. * Sets the value of the alpha mode.
  31679. */
  31680. set: function (value) {
  31681. if (this._alphaMode === value) {
  31682. return;
  31683. }
  31684. this._alphaMode = value;
  31685. this.markAsDirty(Material.TextureDirtyFlag);
  31686. },
  31687. enumerable: true,
  31688. configurable: true
  31689. });
  31690. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31691. /**
  31692. * Gets the depth pre-pass value.
  31693. */
  31694. get: function () {
  31695. return this._needDepthPrePass;
  31696. },
  31697. /**
  31698. * Sets the need depth pre-pass value.
  31699. */
  31700. set: function (value) {
  31701. if (this._needDepthPrePass === value) {
  31702. return;
  31703. }
  31704. this._needDepthPrePass = value;
  31705. if (this._needDepthPrePass) {
  31706. this.checkReadyOnEveryCall = true;
  31707. }
  31708. },
  31709. enumerable: true,
  31710. configurable: true
  31711. });
  31712. Object.defineProperty(Material.prototype, "fogEnabled", {
  31713. /**
  31714. * Gets the value of the fog enabled state.
  31715. */
  31716. get: function () {
  31717. return this._fogEnabled;
  31718. },
  31719. /**
  31720. * Sets the state for enabling fog.
  31721. */
  31722. set: function (value) {
  31723. if (this._fogEnabled === value) {
  31724. return;
  31725. }
  31726. this._fogEnabled = value;
  31727. this.markAsDirty(Material.MiscDirtyFlag);
  31728. },
  31729. enumerable: true,
  31730. configurable: true
  31731. });
  31732. Object.defineProperty(Material.prototype, "wireframe", {
  31733. /**
  31734. * Gets a value specifying if wireframe mode is enabled.
  31735. */
  31736. get: function () {
  31737. switch (this._fillMode) {
  31738. case Material.WireFrameFillMode:
  31739. case Material.LineListDrawMode:
  31740. case Material.LineLoopDrawMode:
  31741. case Material.LineStripDrawMode:
  31742. return true;
  31743. }
  31744. return this._scene.forceWireframe;
  31745. },
  31746. /**
  31747. * Sets the state of wireframe mode.
  31748. */
  31749. set: function (value) {
  31750. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31751. },
  31752. enumerable: true,
  31753. configurable: true
  31754. });
  31755. Object.defineProperty(Material.prototype, "pointsCloud", {
  31756. /**
  31757. * Gets the value specifying if point clouds are enabled.
  31758. */
  31759. get: function () {
  31760. switch (this._fillMode) {
  31761. case Material.PointFillMode:
  31762. case Material.PointListDrawMode:
  31763. return true;
  31764. }
  31765. return this._scene.forcePointsCloud;
  31766. },
  31767. /**
  31768. * Sets the state of point cloud mode.
  31769. */
  31770. set: function (value) {
  31771. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31772. },
  31773. enumerable: true,
  31774. configurable: true
  31775. });
  31776. Object.defineProperty(Material.prototype, "fillMode", {
  31777. /**
  31778. * Gets the material fill mode.
  31779. */
  31780. get: function () {
  31781. return this._fillMode;
  31782. },
  31783. /**
  31784. * Sets the material fill mode.
  31785. */
  31786. set: function (value) {
  31787. if (this._fillMode === value) {
  31788. return;
  31789. }
  31790. this._fillMode = value;
  31791. this.markAsDirty(Material.MiscDirtyFlag);
  31792. },
  31793. enumerable: true,
  31794. configurable: true
  31795. });
  31796. /**
  31797. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31798. * subclasses should override adding information pertainent to themselves.
  31799. * @returns - String with material information.
  31800. */
  31801. Material.prototype.toString = function (fullDetails) {
  31802. var ret = "Name: " + this.name;
  31803. if (fullDetails) {
  31804. }
  31805. return ret;
  31806. };
  31807. /**
  31808. * Gets the class name of the material.
  31809. * @returns - String with the class name of the material.
  31810. */
  31811. Material.prototype.getClassName = function () {
  31812. return "Material";
  31813. };
  31814. Object.defineProperty(Material.prototype, "isFrozen", {
  31815. /**
  31816. * Specifies if updates for the material been locked.
  31817. */
  31818. get: function () {
  31819. return this.checkReadyOnlyOnce;
  31820. },
  31821. enumerable: true,
  31822. configurable: true
  31823. });
  31824. /**
  31825. * Locks updates for the material.
  31826. */
  31827. Material.prototype.freeze = function () {
  31828. this.checkReadyOnlyOnce = true;
  31829. };
  31830. /**
  31831. * Unlocks updates for the material.
  31832. */
  31833. Material.prototype.unfreeze = function () {
  31834. this.checkReadyOnlyOnce = false;
  31835. };
  31836. /**
  31837. * Specifies if the material is ready to be used.
  31838. * @param mesh - BJS mesh.
  31839. * @param useInstances - Specifies if instances should be used.
  31840. * @returns - Boolean indicating if the material is ready to be used.
  31841. */
  31842. Material.prototype.isReady = function (mesh, useInstances) {
  31843. return true;
  31844. };
  31845. /**
  31846. * Specifies that the submesh is ready to be used.
  31847. * @param mesh - BJS mesh.
  31848. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31849. * @param useInstances - Specifies that instances should be used.
  31850. * @returns - boolean indicating that the submesh is ready or not.
  31851. */
  31852. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31853. return false;
  31854. };
  31855. /**
  31856. * Returns the material effect.
  31857. * @returns - Nullable material effect.
  31858. */
  31859. Material.prototype.getEffect = function () {
  31860. return this._effect;
  31861. };
  31862. /**
  31863. * Returns the BJS scene.
  31864. * @returns - BJS Scene.
  31865. */
  31866. Material.prototype.getScene = function () {
  31867. return this._scene;
  31868. };
  31869. /**
  31870. * Specifies if the material will require alpha blending
  31871. * @returns - Boolean specifying if alpha blending is needed.
  31872. */
  31873. Material.prototype.needAlphaBlending = function () {
  31874. return (this.alpha < 1.0);
  31875. };
  31876. /**
  31877. * Specifies if the mesh will require alpha blending.
  31878. * @param mesh - BJS mesh.
  31879. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31880. */
  31881. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31882. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31883. };
  31884. /**
  31885. * Specifies if this material should be rendered in alpha test mode.
  31886. * @returns - Boolean specifying if an alpha test is needed.
  31887. */
  31888. Material.prototype.needAlphaTesting = function () {
  31889. return false;
  31890. };
  31891. /**
  31892. * Gets the texture used for the alpha test.
  31893. * @returns - Nullable alpha test texture.
  31894. */
  31895. Material.prototype.getAlphaTestTexture = function () {
  31896. return null;
  31897. };
  31898. /**
  31899. * Marks the material to indicate that it needs to be re-calculated.
  31900. */
  31901. Material.prototype.markDirty = function () {
  31902. this._wasPreviouslyReady = false;
  31903. };
  31904. Material.prototype._preBind = function (effect, overrideOrientation) {
  31905. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31906. var engine = this._scene.getEngine();
  31907. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31908. var reverse = orientation === Material.ClockWiseSideOrientation;
  31909. engine.enableEffect(effect ? effect : this._effect);
  31910. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31911. return reverse;
  31912. };
  31913. /**
  31914. * Binds the material to the mesh.
  31915. * @param world - World transformation matrix.
  31916. * @param mesh - Mesh to bind the material to.
  31917. */
  31918. Material.prototype.bind = function (world, mesh) {
  31919. };
  31920. /**
  31921. * Binds the submesh to the material.
  31922. * @param world - World transformation matrix.
  31923. * @param mesh - Mesh containing the submesh.
  31924. * @param subMesh - Submesh to bind the material to.
  31925. */
  31926. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31927. };
  31928. /**
  31929. * Binds the world matrix to the material.
  31930. * @param world - World transformation matrix.
  31931. */
  31932. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31933. };
  31934. /**
  31935. * Binds the scene's uniform buffer to the effect.
  31936. * @param effect - Effect to bind to the scene uniform buffer.
  31937. * @param sceneUbo - Scene uniform buffer.
  31938. */
  31939. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31940. sceneUbo.bindToEffect(effect, "Scene");
  31941. };
  31942. /**
  31943. * Binds the view matrix to the effect.
  31944. * @param effect - Effect to bind the view matrix to.
  31945. */
  31946. Material.prototype.bindView = function (effect) {
  31947. if (!this._useUBO) {
  31948. effect.setMatrix("view", this.getScene().getViewMatrix());
  31949. }
  31950. else {
  31951. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31952. }
  31953. };
  31954. /**
  31955. * Binds the view projection matrix to the effect.
  31956. * @param effect - Effect to bind the view projection matrix to.
  31957. */
  31958. Material.prototype.bindViewProjection = function (effect) {
  31959. if (!this._useUBO) {
  31960. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31961. }
  31962. else {
  31963. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31964. }
  31965. };
  31966. /**
  31967. * Specifies if material alpha testing should be turned on for the mesh.
  31968. * @param mesh - BJS mesh.
  31969. */
  31970. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31971. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31972. };
  31973. /**
  31974. * Processes to execute after binding the material to a mesh.
  31975. * @param mesh - BJS mesh.
  31976. */
  31977. Material.prototype._afterBind = function (mesh) {
  31978. this._scene._cachedMaterial = this;
  31979. if (mesh) {
  31980. this._scene._cachedVisibility = mesh.visibility;
  31981. }
  31982. else {
  31983. this._scene._cachedVisibility = 1;
  31984. }
  31985. if (mesh) {
  31986. this.onBindObservable.notifyObservers(mesh);
  31987. }
  31988. if (this.disableDepthWrite) {
  31989. var engine = this._scene.getEngine();
  31990. this._cachedDepthWriteState = engine.getDepthWrite();
  31991. engine.setDepthWrite(false);
  31992. }
  31993. };
  31994. /**
  31995. * Unbinds the material from the mesh.
  31996. */
  31997. Material.prototype.unbind = function () {
  31998. this.onUnBindObservable.notifyObservers(this);
  31999. if (this.disableDepthWrite) {
  32000. var engine = this._scene.getEngine();
  32001. engine.setDepthWrite(this._cachedDepthWriteState);
  32002. }
  32003. };
  32004. /**
  32005. * Gets the active textures from the material.
  32006. * @returns - Array of textures.
  32007. */
  32008. Material.prototype.getActiveTextures = function () {
  32009. return [];
  32010. };
  32011. /**
  32012. * Specifies if the material uses a texture.
  32013. * @param texture - Texture to check against the material.
  32014. * @returns - Boolean specifying if the material uses the texture.
  32015. */
  32016. Material.prototype.hasTexture = function (texture) {
  32017. return false;
  32018. };
  32019. /**
  32020. * Makes a duplicate of the material, and gives it a new name.
  32021. * @param name - Name to call the duplicated material.
  32022. * @returns - Nullable cloned material
  32023. */
  32024. Material.prototype.clone = function (name) {
  32025. return null;
  32026. };
  32027. /**
  32028. * Gets the meshes bound to the material.
  32029. * @returns - Array of meshes bound to the material.
  32030. */
  32031. Material.prototype.getBindedMeshes = function () {
  32032. var result = new Array();
  32033. for (var index = 0; index < this._scene.meshes.length; index++) {
  32034. var mesh = this._scene.meshes[index];
  32035. if (mesh.material === this) {
  32036. result.push(mesh);
  32037. }
  32038. }
  32039. return result;
  32040. };
  32041. /**
  32042. * Force shader compilation
  32043. * @param mesh - BJS mesh.
  32044. * @param onCompiled - function to execute once the material is compiled.
  32045. * @param options - options to pass to this function.
  32046. */
  32047. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  32048. var _this = this;
  32049. var localOptions = __assign({ clipPlane: false }, options);
  32050. var subMesh = new BABYLON.BaseSubMesh();
  32051. var scene = this.getScene();
  32052. var checkReady = function () {
  32053. if (!_this._scene || !_this._scene.getEngine()) {
  32054. return;
  32055. }
  32056. if (subMesh._materialDefines) {
  32057. subMesh._materialDefines._renderId = -1;
  32058. }
  32059. var clipPlaneState = scene.clipPlane;
  32060. if (localOptions.clipPlane) {
  32061. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  32062. }
  32063. if (_this.storeEffectOnSubMeshes) {
  32064. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  32065. if (onCompiled) {
  32066. onCompiled(_this);
  32067. }
  32068. }
  32069. else {
  32070. setTimeout(checkReady, 16);
  32071. }
  32072. }
  32073. else {
  32074. if (_this.isReady(mesh)) {
  32075. if (onCompiled) {
  32076. onCompiled(_this);
  32077. }
  32078. }
  32079. else {
  32080. setTimeout(checkReady, 16);
  32081. }
  32082. }
  32083. if (localOptions.clipPlane) {
  32084. scene.clipPlane = clipPlaneState;
  32085. }
  32086. };
  32087. checkReady();
  32088. };
  32089. /**
  32090. * Force shader compilation.
  32091. * @param mesh The mesh that will use this material
  32092. * @param options Additional options for compiling the shaders
  32093. * @returns A promise that resolves when the compilation completes
  32094. */
  32095. Material.prototype.forceCompilationAsync = function (mesh, options) {
  32096. var _this = this;
  32097. return new Promise(function (resolve) {
  32098. _this.forceCompilation(mesh, function () {
  32099. resolve();
  32100. }, options);
  32101. });
  32102. };
  32103. /**
  32104. * Marks a define in the material to indicate that it needs to be re-computed.
  32105. * @param flag - Material define flag.
  32106. */
  32107. Material.prototype.markAsDirty = function (flag) {
  32108. if (flag & Material.TextureDirtyFlag) {
  32109. this._markAllSubMeshesAsTexturesDirty();
  32110. }
  32111. if (flag & Material.LightDirtyFlag) {
  32112. this._markAllSubMeshesAsLightsDirty();
  32113. }
  32114. if (flag & Material.FresnelDirtyFlag) {
  32115. this._markAllSubMeshesAsFresnelDirty();
  32116. }
  32117. if (flag & Material.AttributesDirtyFlag) {
  32118. this._markAllSubMeshesAsAttributesDirty();
  32119. }
  32120. if (flag & Material.MiscDirtyFlag) {
  32121. this._markAllSubMeshesAsMiscDirty();
  32122. }
  32123. this.getScene().resetCachedMaterial();
  32124. };
  32125. /**
  32126. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  32127. * @param func - function which checks material defines against the submeshes.
  32128. */
  32129. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  32130. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  32131. var mesh = _a[_i];
  32132. if (!mesh.subMeshes) {
  32133. continue;
  32134. }
  32135. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  32136. var subMesh = _c[_b];
  32137. if (subMesh.getMaterial() !== this) {
  32138. continue;
  32139. }
  32140. if (!subMesh._materialDefines) {
  32141. continue;
  32142. }
  32143. func(subMesh._materialDefines);
  32144. }
  32145. }
  32146. };
  32147. /**
  32148. * Indicates that image processing needs to be re-calculated for all submeshes.
  32149. */
  32150. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  32151. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  32152. };
  32153. /**
  32154. * Indicates that textures need to be re-calculated for all submeshes.
  32155. */
  32156. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  32157. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  32158. };
  32159. /**
  32160. * Indicates that fresnel needs to be re-calculated for all submeshes.
  32161. */
  32162. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  32163. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  32164. };
  32165. /**
  32166. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  32167. */
  32168. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  32169. this._markAllSubMeshesAsDirty(function (defines) {
  32170. defines.markAsFresnelDirty();
  32171. defines.markAsMiscDirty();
  32172. });
  32173. };
  32174. /**
  32175. * Indicates that lights need to be re-calculated for all submeshes.
  32176. */
  32177. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  32178. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  32179. };
  32180. /**
  32181. * Indicates that attributes need to be re-calculated for all submeshes.
  32182. */
  32183. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  32184. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  32185. };
  32186. /**
  32187. * Indicates that misc needs to be re-calculated for all submeshes.
  32188. */
  32189. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  32190. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  32191. };
  32192. /**
  32193. * Indicates that textures and misc need to be re-calculated for all submeshes.
  32194. */
  32195. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  32196. this._markAllSubMeshesAsDirty(function (defines) {
  32197. defines.markAsTexturesDirty();
  32198. defines.markAsMiscDirty();
  32199. });
  32200. };
  32201. /**
  32202. * Disposes the material.
  32203. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  32204. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  32205. */
  32206. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32207. // Animations
  32208. this.getScene().stopAnimation(this);
  32209. this.getScene().freeProcessedMaterials();
  32210. // Remove from scene
  32211. var index = this._scene.materials.indexOf(this);
  32212. if (index >= 0) {
  32213. this._scene.materials.splice(index, 1);
  32214. }
  32215. // Remove from meshes
  32216. for (index = 0; index < this._scene.meshes.length; index++) {
  32217. var mesh = this._scene.meshes[index];
  32218. if (mesh.material === this) {
  32219. mesh.material = null;
  32220. if (mesh.geometry) {
  32221. var geometry = (mesh.geometry);
  32222. if (this.storeEffectOnSubMeshes) {
  32223. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  32224. var subMesh = _a[_i];
  32225. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  32226. if (forceDisposeEffect && subMesh._materialEffect) {
  32227. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  32228. }
  32229. }
  32230. }
  32231. else {
  32232. geometry._releaseVertexArrayObject(this._effect);
  32233. }
  32234. }
  32235. }
  32236. }
  32237. this._uniformBuffer.dispose();
  32238. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  32239. if (forceDisposeEffect && this._effect) {
  32240. if (!this.storeEffectOnSubMeshes) {
  32241. this._scene.getEngine()._releaseEffect(this._effect);
  32242. }
  32243. this._effect = null;
  32244. }
  32245. // Callback
  32246. this.onDisposeObservable.notifyObservers(this);
  32247. this.onDisposeObservable.clear();
  32248. this.onBindObservable.clear();
  32249. this.onUnBindObservable.clear();
  32250. };
  32251. /**
  32252. * Serializes this material.
  32253. * @returns - serialized material object.
  32254. */
  32255. Material.prototype.serialize = function () {
  32256. return BABYLON.SerializationHelper.Serialize(this);
  32257. };
  32258. /**
  32259. * Creates a MultiMaterial from parse MultiMaterial data.
  32260. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  32261. * @param scene - BJS scene.
  32262. * @returns - MultiMaterial.
  32263. */
  32264. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  32265. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  32266. multiMaterial.id = parsedMultiMaterial.id;
  32267. if (BABYLON.Tags) {
  32268. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  32269. }
  32270. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  32271. var subMatId = parsedMultiMaterial.materials[matIndex];
  32272. if (subMatId) {
  32273. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  32274. }
  32275. else {
  32276. multiMaterial.subMaterials.push(null);
  32277. }
  32278. }
  32279. return multiMaterial;
  32280. };
  32281. /**
  32282. * Creates a material from parsed material data.
  32283. * @param parsedMaterial - Parsed material data.
  32284. * @param scene - BJS scene.
  32285. * @param rootUrl - Root URL containing the material information.
  32286. * @returns - Parsed material.
  32287. */
  32288. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  32289. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  32290. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  32291. }
  32292. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  32293. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  32294. if (!BABYLON.LegacyPBRMaterial) {
  32295. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  32296. return;
  32297. }
  32298. }
  32299. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  32300. return materialType.Parse(parsedMaterial, scene, rootUrl);
  32301. ;
  32302. };
  32303. // Triangle views
  32304. Material._TriangleFillMode = 0;
  32305. Material._WireFrameFillMode = 1;
  32306. Material._PointFillMode = 2;
  32307. // Draw modes
  32308. Material._PointListDrawMode = 3;
  32309. Material._LineListDrawMode = 4;
  32310. Material._LineLoopDrawMode = 5;
  32311. Material._LineStripDrawMode = 6;
  32312. Material._TriangleStripDrawMode = 7;
  32313. Material._TriangleFanDrawMode = 8;
  32314. /**
  32315. * Stores the clock-wise side orientation.
  32316. */
  32317. Material._ClockWiseSideOrientation = 0;
  32318. /**
  32319. * Stores the counter clock-wise side orientation.
  32320. */
  32321. Material._CounterClockWiseSideOrientation = 1;
  32322. /**
  32323. * The dirty texture flag value.
  32324. */
  32325. Material._TextureDirtyFlag = 1;
  32326. /**
  32327. * The dirty light flag value.
  32328. */
  32329. Material._LightDirtyFlag = 2;
  32330. /**
  32331. * The dirty fresnel flag value.
  32332. */
  32333. Material._FresnelDirtyFlag = 4;
  32334. /**
  32335. * The dirty attribute flag value.
  32336. */
  32337. Material._AttributesDirtyFlag = 8;
  32338. /**
  32339. * The dirty misc flag value.
  32340. */
  32341. Material._MiscDirtyFlag = 16;
  32342. __decorate([
  32343. BABYLON.serialize()
  32344. ], Material.prototype, "id", void 0);
  32345. __decorate([
  32346. BABYLON.serialize()
  32347. ], Material.prototype, "name", void 0);
  32348. __decorate([
  32349. BABYLON.serialize()
  32350. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  32351. __decorate([
  32352. BABYLON.serialize()
  32353. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  32354. __decorate([
  32355. BABYLON.serialize()
  32356. ], Material.prototype, "state", void 0);
  32357. __decorate([
  32358. BABYLON.serialize("alpha")
  32359. ], Material.prototype, "_alpha", void 0);
  32360. __decorate([
  32361. BABYLON.serialize("backFaceCulling")
  32362. ], Material.prototype, "_backFaceCulling", void 0);
  32363. __decorate([
  32364. BABYLON.serialize()
  32365. ], Material.prototype, "sideOrientation", void 0);
  32366. __decorate([
  32367. BABYLON.serialize("alphaMode")
  32368. ], Material.prototype, "_alphaMode", void 0);
  32369. __decorate([
  32370. BABYLON.serialize()
  32371. ], Material.prototype, "_needDepthPrePass", void 0);
  32372. __decorate([
  32373. BABYLON.serialize()
  32374. ], Material.prototype, "disableDepthWrite", void 0);
  32375. __decorate([
  32376. BABYLON.serialize()
  32377. ], Material.prototype, "forceDepthWrite", void 0);
  32378. __decorate([
  32379. BABYLON.serialize()
  32380. ], Material.prototype, "separateCullingPass", void 0);
  32381. __decorate([
  32382. BABYLON.serialize("fogEnabled")
  32383. ], Material.prototype, "_fogEnabled", void 0);
  32384. __decorate([
  32385. BABYLON.serialize()
  32386. ], Material.prototype, "pointSize", void 0);
  32387. __decorate([
  32388. BABYLON.serialize()
  32389. ], Material.prototype, "zOffset", void 0);
  32390. __decorate([
  32391. BABYLON.serialize()
  32392. ], Material.prototype, "wireframe", null);
  32393. __decorate([
  32394. BABYLON.serialize()
  32395. ], Material.prototype, "pointsCloud", null);
  32396. __decorate([
  32397. BABYLON.serialize()
  32398. ], Material.prototype, "fillMode", null);
  32399. return Material;
  32400. }());
  32401. BABYLON.Material = Material;
  32402. })(BABYLON || (BABYLON = {}));
  32403. //# sourceMappingURL=babylon.material.js.map
  32404. "use strict";
  32405. var BABYLON;
  32406. (function (BABYLON) {
  32407. var UniformBuffer = /** @class */ (function () {
  32408. /**
  32409. * Uniform buffer objects.
  32410. *
  32411. * Handles blocks of uniform on the GPU.
  32412. *
  32413. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32414. *
  32415. * For more information, please refer to :
  32416. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32417. */
  32418. function UniformBuffer(engine, data, dynamic) {
  32419. this._engine = engine;
  32420. this._noUBO = !engine.supportsUniformBuffers;
  32421. this._dynamic = dynamic;
  32422. this._data = data || [];
  32423. this._uniformLocations = {};
  32424. this._uniformSizes = {};
  32425. this._uniformLocationPointer = 0;
  32426. this._needSync = false;
  32427. if (this._noUBO) {
  32428. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32429. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32430. this.updateFloat = this._updateFloatForEffect;
  32431. this.updateFloat2 = this._updateFloat2ForEffect;
  32432. this.updateFloat3 = this._updateFloat3ForEffect;
  32433. this.updateFloat4 = this._updateFloat4ForEffect;
  32434. this.updateMatrix = this._updateMatrixForEffect;
  32435. this.updateVector3 = this._updateVector3ForEffect;
  32436. this.updateVector4 = this._updateVector4ForEffect;
  32437. this.updateColor3 = this._updateColor3ForEffect;
  32438. this.updateColor4 = this._updateColor4ForEffect;
  32439. }
  32440. else {
  32441. this._engine._uniformBuffers.push(this);
  32442. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32443. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32444. this.updateFloat = this._updateFloatForUniform;
  32445. this.updateFloat2 = this._updateFloat2ForUniform;
  32446. this.updateFloat3 = this._updateFloat3ForUniform;
  32447. this.updateFloat4 = this._updateFloat4ForUniform;
  32448. this.updateMatrix = this._updateMatrixForUniform;
  32449. this.updateVector3 = this._updateVector3ForUniform;
  32450. this.updateVector4 = this._updateVector4ForUniform;
  32451. this.updateColor3 = this._updateColor3ForUniform;
  32452. this.updateColor4 = this._updateColor4ForUniform;
  32453. }
  32454. }
  32455. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32456. // Properties
  32457. /**
  32458. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32459. * or just falling back on setUniformXXX calls.
  32460. */
  32461. get: function () {
  32462. return !this._noUBO;
  32463. },
  32464. enumerable: true,
  32465. configurable: true
  32466. });
  32467. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32468. /**
  32469. * Indicates if the WebGL underlying uniform buffer is in sync
  32470. * with the javascript cache data.
  32471. */
  32472. get: function () {
  32473. return !this._needSync;
  32474. },
  32475. enumerable: true,
  32476. configurable: true
  32477. });
  32478. /**
  32479. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32480. * Also, a dynamic UniformBuffer will disable cache verification and always
  32481. * update the underlying WebGL uniform buffer to the GPU.
  32482. */
  32483. UniformBuffer.prototype.isDynamic = function () {
  32484. return this._dynamic !== undefined;
  32485. };
  32486. /**
  32487. * The data cache on JS side.
  32488. */
  32489. UniformBuffer.prototype.getData = function () {
  32490. return this._bufferData;
  32491. };
  32492. /**
  32493. * The underlying WebGL Uniform buffer.
  32494. */
  32495. UniformBuffer.prototype.getBuffer = function () {
  32496. return this._buffer;
  32497. };
  32498. /**
  32499. * std140 layout specifies how to align data within an UBO structure.
  32500. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32501. * for specs.
  32502. */
  32503. UniformBuffer.prototype._fillAlignment = function (size) {
  32504. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32505. // and 4x4 matrices
  32506. // TODO : change if other types are used
  32507. var alignment;
  32508. if (size <= 2) {
  32509. alignment = size;
  32510. }
  32511. else {
  32512. alignment = 4;
  32513. }
  32514. if ((this._uniformLocationPointer % alignment) !== 0) {
  32515. var oldPointer = this._uniformLocationPointer;
  32516. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32517. var diff = this._uniformLocationPointer - oldPointer;
  32518. for (var i = 0; i < diff; i++) {
  32519. this._data.push(0);
  32520. }
  32521. }
  32522. };
  32523. /**
  32524. * Adds an uniform in the buffer.
  32525. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32526. * for the layout to be correct !
  32527. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32528. * @param {number|number[]} size Data size, or data directly.
  32529. */
  32530. UniformBuffer.prototype.addUniform = function (name, size) {
  32531. if (this._noUBO) {
  32532. return;
  32533. }
  32534. if (this._uniformLocations[name] !== undefined) {
  32535. // Already existing uniform
  32536. return;
  32537. }
  32538. // This function must be called in the order of the shader layout !
  32539. // size can be the size of the uniform, or data directly
  32540. var data;
  32541. if (size instanceof Array) {
  32542. data = size;
  32543. size = data.length;
  32544. }
  32545. else {
  32546. size = size;
  32547. data = [];
  32548. // Fill with zeros
  32549. for (var i = 0; i < size; i++) {
  32550. data.push(0);
  32551. }
  32552. }
  32553. this._fillAlignment(size);
  32554. this._uniformSizes[name] = size;
  32555. this._uniformLocations[name] = this._uniformLocationPointer;
  32556. this._uniformLocationPointer += size;
  32557. for (var i = 0; i < size; i++) {
  32558. this._data.push(data[i]);
  32559. }
  32560. this._needSync = true;
  32561. };
  32562. /**
  32563. * Wrapper for addUniform.
  32564. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32565. * @param {Matrix} mat A 4x4 matrix.
  32566. */
  32567. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32568. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32569. };
  32570. /**
  32571. * Wrapper for addUniform.
  32572. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32573. * @param {number} x
  32574. * @param {number} y
  32575. */
  32576. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32577. var temp = [x, y];
  32578. this.addUniform(name, temp);
  32579. };
  32580. /**
  32581. * Wrapper for addUniform.
  32582. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32583. * @param {number} x
  32584. * @param {number} y
  32585. * @param {number} z
  32586. */
  32587. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32588. var temp = [x, y, z];
  32589. this.addUniform(name, temp);
  32590. };
  32591. /**
  32592. * Wrapper for addUniform.
  32593. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32594. * @param {Color3} color
  32595. */
  32596. UniformBuffer.prototype.addColor3 = function (name, color) {
  32597. var temp = new Array();
  32598. color.toArray(temp);
  32599. this.addUniform(name, temp);
  32600. };
  32601. /**
  32602. * Wrapper for addUniform.
  32603. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32604. * @param {Color3} color
  32605. * @param {number} alpha
  32606. */
  32607. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32608. var temp = new Array();
  32609. color.toArray(temp);
  32610. temp.push(alpha);
  32611. this.addUniform(name, temp);
  32612. };
  32613. /**
  32614. * Wrapper for addUniform.
  32615. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32616. * @param {Vector3} vector
  32617. */
  32618. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32619. var temp = new Array();
  32620. vector.toArray(temp);
  32621. this.addUniform(name, temp);
  32622. };
  32623. /**
  32624. * Wrapper for addUniform.
  32625. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32626. */
  32627. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32628. this.addUniform(name, 12);
  32629. };
  32630. /**
  32631. * Wrapper for addUniform.
  32632. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32633. */
  32634. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32635. this.addUniform(name, 8);
  32636. };
  32637. /**
  32638. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32639. */
  32640. UniformBuffer.prototype.create = function () {
  32641. if (this._noUBO) {
  32642. return;
  32643. }
  32644. if (this._buffer) {
  32645. return; // nothing to do
  32646. }
  32647. // See spec, alignment must be filled as a vec4
  32648. this._fillAlignment(4);
  32649. this._bufferData = new Float32Array(this._data);
  32650. this._rebuild();
  32651. this._needSync = true;
  32652. };
  32653. UniformBuffer.prototype._rebuild = function () {
  32654. if (this._noUBO) {
  32655. return;
  32656. }
  32657. if (this._dynamic) {
  32658. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32659. }
  32660. else {
  32661. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32662. }
  32663. };
  32664. /**
  32665. * Updates the WebGL Uniform Buffer on the GPU.
  32666. * If the `dynamic` flag is set to true, no cache comparison is done.
  32667. * Otherwise, the buffer will be updated only if the cache differs.
  32668. */
  32669. UniformBuffer.prototype.update = function () {
  32670. if (!this._buffer) {
  32671. this.create();
  32672. return;
  32673. }
  32674. if (!this._dynamic && !this._needSync) {
  32675. return;
  32676. }
  32677. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32678. this._needSync = false;
  32679. };
  32680. /**
  32681. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32682. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32683. * @param {number[]|Float32Array} data Flattened data
  32684. * @param {number} size Size of the data.
  32685. */
  32686. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32687. var location = this._uniformLocations[uniformName];
  32688. if (location === undefined) {
  32689. if (this._buffer) {
  32690. // Cannot add an uniform if the buffer is already created
  32691. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32692. return;
  32693. }
  32694. this.addUniform(uniformName, size);
  32695. location = this._uniformLocations[uniformName];
  32696. }
  32697. if (!this._buffer) {
  32698. this.create();
  32699. }
  32700. if (!this._dynamic) {
  32701. // Cache for static uniform buffers
  32702. var changed = false;
  32703. for (var i = 0; i < size; i++) {
  32704. if (this._bufferData[location + i] !== data[i]) {
  32705. changed = true;
  32706. this._bufferData[location + i] = data[i];
  32707. }
  32708. }
  32709. this._needSync = this._needSync || changed;
  32710. }
  32711. else {
  32712. // No cache for dynamic
  32713. for (var i = 0; i < size; i++) {
  32714. this._bufferData[location + i] = data[i];
  32715. }
  32716. }
  32717. };
  32718. // Update methods
  32719. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32720. // To match std140, matrix must be realigned
  32721. for (var i = 0; i < 3; i++) {
  32722. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32723. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32724. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32725. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32726. }
  32727. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32728. };
  32729. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32730. this._currentEffect.setMatrix3x3(name, matrix);
  32731. };
  32732. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32733. this._currentEffect.setMatrix2x2(name, matrix);
  32734. };
  32735. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32736. // To match std140, matrix must be realigned
  32737. for (var i = 0; i < 2; i++) {
  32738. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32739. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32740. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32741. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32742. }
  32743. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32744. };
  32745. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32746. this._currentEffect.setFloat(name, x);
  32747. };
  32748. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32749. UniformBuffer._tempBuffer[0] = x;
  32750. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32751. };
  32752. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32753. if (suffix === void 0) { suffix = ""; }
  32754. this._currentEffect.setFloat2(name + suffix, x, y);
  32755. };
  32756. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32757. if (suffix === void 0) { suffix = ""; }
  32758. UniformBuffer._tempBuffer[0] = x;
  32759. UniformBuffer._tempBuffer[1] = y;
  32760. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32761. };
  32762. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32763. if (suffix === void 0) { suffix = ""; }
  32764. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32765. };
  32766. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32767. if (suffix === void 0) { suffix = ""; }
  32768. UniformBuffer._tempBuffer[0] = x;
  32769. UniformBuffer._tempBuffer[1] = y;
  32770. UniformBuffer._tempBuffer[2] = z;
  32771. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32772. };
  32773. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32774. if (suffix === void 0) { suffix = ""; }
  32775. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32776. };
  32777. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32778. if (suffix === void 0) { suffix = ""; }
  32779. UniformBuffer._tempBuffer[0] = x;
  32780. UniformBuffer._tempBuffer[1] = y;
  32781. UniformBuffer._tempBuffer[2] = z;
  32782. UniformBuffer._tempBuffer[3] = w;
  32783. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32784. };
  32785. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32786. this._currentEffect.setMatrix(name, mat);
  32787. };
  32788. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32789. this.updateUniform(name, mat.toArray(), 16);
  32790. };
  32791. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32792. this._currentEffect.setVector3(name, vector);
  32793. };
  32794. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32795. vector.toArray(UniformBuffer._tempBuffer);
  32796. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32797. };
  32798. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32799. this._currentEffect.setVector4(name, vector);
  32800. };
  32801. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32802. vector.toArray(UniformBuffer._tempBuffer);
  32803. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32804. };
  32805. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32806. if (suffix === void 0) { suffix = ""; }
  32807. this._currentEffect.setColor3(name + suffix, color);
  32808. };
  32809. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32810. if (suffix === void 0) { suffix = ""; }
  32811. color.toArray(UniformBuffer._tempBuffer);
  32812. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32813. };
  32814. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32815. if (suffix === void 0) { suffix = ""; }
  32816. this._currentEffect.setColor4(name + suffix, color, alpha);
  32817. };
  32818. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32819. if (suffix === void 0) { suffix = ""; }
  32820. color.toArray(UniformBuffer._tempBuffer);
  32821. UniformBuffer._tempBuffer[3] = alpha;
  32822. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32823. };
  32824. /**
  32825. * Sets a sampler uniform on the effect.
  32826. * @param {string} name Name of the sampler.
  32827. * @param {Texture} texture
  32828. */
  32829. UniformBuffer.prototype.setTexture = function (name, texture) {
  32830. this._currentEffect.setTexture(name, texture);
  32831. };
  32832. /**
  32833. * Directly updates the value of the uniform in the cache AND on the GPU.
  32834. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32835. * @param {number[]|Float32Array} data Flattened data
  32836. */
  32837. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32838. this.updateUniform(uniformName, data, data.length);
  32839. this.update();
  32840. };
  32841. /**
  32842. * Binds this uniform buffer to an effect.
  32843. * @param {Effect} effect
  32844. * @param {string} name Name of the uniform block in the shader.
  32845. */
  32846. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32847. this._currentEffect = effect;
  32848. if (this._noUBO || !this._buffer) {
  32849. return;
  32850. }
  32851. effect.bindUniformBuffer(this._buffer, name);
  32852. };
  32853. /**
  32854. * Disposes the uniform buffer.
  32855. */
  32856. UniformBuffer.prototype.dispose = function () {
  32857. if (this._noUBO) {
  32858. return;
  32859. }
  32860. var index = this._engine._uniformBuffers.indexOf(this);
  32861. if (index !== -1) {
  32862. this._engine._uniformBuffers.splice(index, 1);
  32863. }
  32864. if (!this._buffer) {
  32865. return;
  32866. }
  32867. if (this._engine._releaseBuffer(this._buffer)) {
  32868. this._buffer = null;
  32869. }
  32870. };
  32871. // Pool for avoiding memory leaks
  32872. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32873. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32874. return UniformBuffer;
  32875. }());
  32876. BABYLON.UniformBuffer = UniformBuffer;
  32877. })(BABYLON || (BABYLON = {}));
  32878. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32879. "use strict";
  32880. var BABYLON;
  32881. (function (BABYLON) {
  32882. var VertexData = /** @class */ (function () {
  32883. function VertexData() {
  32884. }
  32885. VertexData.prototype.set = function (data, kind) {
  32886. switch (kind) {
  32887. case BABYLON.VertexBuffer.PositionKind:
  32888. this.positions = data;
  32889. break;
  32890. case BABYLON.VertexBuffer.NormalKind:
  32891. this.normals = data;
  32892. break;
  32893. case BABYLON.VertexBuffer.TangentKind:
  32894. this.tangents = data;
  32895. break;
  32896. case BABYLON.VertexBuffer.UVKind:
  32897. this.uvs = data;
  32898. break;
  32899. case BABYLON.VertexBuffer.UV2Kind:
  32900. this.uvs2 = data;
  32901. break;
  32902. case BABYLON.VertexBuffer.UV3Kind:
  32903. this.uvs3 = data;
  32904. break;
  32905. case BABYLON.VertexBuffer.UV4Kind:
  32906. this.uvs4 = data;
  32907. break;
  32908. case BABYLON.VertexBuffer.UV5Kind:
  32909. this.uvs5 = data;
  32910. break;
  32911. case BABYLON.VertexBuffer.UV6Kind:
  32912. this.uvs6 = data;
  32913. break;
  32914. case BABYLON.VertexBuffer.ColorKind:
  32915. this.colors = data;
  32916. break;
  32917. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32918. this.matricesIndices = data;
  32919. break;
  32920. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32921. this.matricesWeights = data;
  32922. break;
  32923. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32924. this.matricesIndicesExtra = data;
  32925. break;
  32926. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32927. this.matricesWeightsExtra = data;
  32928. break;
  32929. }
  32930. };
  32931. /**
  32932. * Associates the vertexData to the passed Mesh.
  32933. * Sets it as updatable or not (default `false`).
  32934. * Returns the VertexData.
  32935. */
  32936. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32937. this._applyTo(mesh, updatable);
  32938. return this;
  32939. };
  32940. /**
  32941. * Associates the vertexData to the passed Geometry.
  32942. * Sets it as updatable or not (default `false`).
  32943. * Returns the VertexData.
  32944. */
  32945. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32946. this._applyTo(geometry, updatable);
  32947. return this;
  32948. };
  32949. /**
  32950. * Updates the associated mesh.
  32951. * Returns the VertexData.
  32952. */
  32953. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32954. this._update(mesh);
  32955. return this;
  32956. };
  32957. /**
  32958. * Updates the associated geometry.
  32959. * Returns the VertexData.
  32960. */
  32961. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32962. this._update(geometry);
  32963. return this;
  32964. };
  32965. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32966. if (updatable === void 0) { updatable = false; }
  32967. if (this.positions) {
  32968. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32969. }
  32970. if (this.normals) {
  32971. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32972. }
  32973. if (this.tangents) {
  32974. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32975. }
  32976. if (this.uvs) {
  32977. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32978. }
  32979. if (this.uvs2) {
  32980. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32981. }
  32982. if (this.uvs3) {
  32983. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32984. }
  32985. if (this.uvs4) {
  32986. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32987. }
  32988. if (this.uvs5) {
  32989. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32990. }
  32991. if (this.uvs6) {
  32992. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32993. }
  32994. if (this.colors) {
  32995. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32996. }
  32997. if (this.matricesIndices) {
  32998. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32999. }
  33000. if (this.matricesWeights) {
  33001. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  33002. }
  33003. if (this.matricesIndicesExtra) {
  33004. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  33005. }
  33006. if (this.matricesWeightsExtra) {
  33007. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  33008. }
  33009. if (this.indices) {
  33010. meshOrGeometry.setIndices(this.indices, null, updatable);
  33011. }
  33012. return this;
  33013. };
  33014. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  33015. if (this.positions) {
  33016. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  33017. }
  33018. if (this.normals) {
  33019. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  33020. }
  33021. if (this.tangents) {
  33022. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  33023. }
  33024. if (this.uvs) {
  33025. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  33026. }
  33027. if (this.uvs2) {
  33028. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  33029. }
  33030. if (this.uvs3) {
  33031. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  33032. }
  33033. if (this.uvs4) {
  33034. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  33035. }
  33036. if (this.uvs5) {
  33037. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  33038. }
  33039. if (this.uvs6) {
  33040. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  33041. }
  33042. if (this.colors) {
  33043. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  33044. }
  33045. if (this.matricesIndices) {
  33046. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  33047. }
  33048. if (this.matricesWeights) {
  33049. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  33050. }
  33051. if (this.matricesIndicesExtra) {
  33052. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  33053. }
  33054. if (this.matricesWeightsExtra) {
  33055. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  33056. }
  33057. if (this.indices) {
  33058. meshOrGeometry.setIndices(this.indices, null);
  33059. }
  33060. return this;
  33061. };
  33062. /**
  33063. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  33064. * Returns the VertexData.
  33065. */
  33066. VertexData.prototype.transform = function (matrix) {
  33067. var transformed = BABYLON.Vector3.Zero();
  33068. var index;
  33069. if (this.positions) {
  33070. var position = BABYLON.Vector3.Zero();
  33071. for (index = 0; index < this.positions.length; index += 3) {
  33072. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33073. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33074. this.positions[index] = transformed.x;
  33075. this.positions[index + 1] = transformed.y;
  33076. this.positions[index + 2] = transformed.z;
  33077. }
  33078. }
  33079. if (this.normals) {
  33080. var normal = BABYLON.Vector3.Zero();
  33081. for (index = 0; index < this.normals.length; index += 3) {
  33082. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33083. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33084. this.normals[index] = transformed.x;
  33085. this.normals[index + 1] = transformed.y;
  33086. this.normals[index + 2] = transformed.z;
  33087. }
  33088. }
  33089. if (this.tangents) {
  33090. var tangent = BABYLON.Vector4.Zero();
  33091. var tangentTransformed = BABYLON.Vector4.Zero();
  33092. for (index = 0; index < this.tangents.length; index += 4) {
  33093. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  33094. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  33095. this.tangents[index] = tangentTransformed.x;
  33096. this.tangents[index + 1] = tangentTransformed.y;
  33097. this.tangents[index + 2] = tangentTransformed.z;
  33098. this.tangents[index + 3] = tangentTransformed.w;
  33099. }
  33100. }
  33101. return this;
  33102. };
  33103. /**
  33104. * Merges the passed VertexData into the current one.
  33105. * Returns the modified VertexData.
  33106. */
  33107. VertexData.prototype.merge = function (other) {
  33108. this._validate();
  33109. other._validate();
  33110. if (!this.normals !== !other.normals ||
  33111. !this.tangents !== !other.tangents ||
  33112. !this.uvs !== !other.uvs ||
  33113. !this.uvs2 !== !other.uvs2 ||
  33114. !this.uvs3 !== !other.uvs3 ||
  33115. !this.uvs4 !== !other.uvs4 ||
  33116. !this.uvs5 !== !other.uvs5 ||
  33117. !this.uvs6 !== !other.uvs6 ||
  33118. !this.colors !== !other.colors ||
  33119. !this.matricesIndices !== !other.matricesIndices ||
  33120. !this.matricesWeights !== !other.matricesWeights ||
  33121. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  33122. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  33123. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  33124. }
  33125. if (other.indices) {
  33126. if (!this.indices) {
  33127. this.indices = [];
  33128. }
  33129. var offset = this.positions ? this.positions.length / 3 : 0;
  33130. for (var index = 0; index < other.indices.length; index++) {
  33131. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  33132. this.indices.push(other.indices[index] + offset);
  33133. }
  33134. }
  33135. this.positions = this._mergeElement(this.positions, other.positions);
  33136. this.normals = this._mergeElement(this.normals, other.normals);
  33137. this.tangents = this._mergeElement(this.tangents, other.tangents);
  33138. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33139. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33140. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33141. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33142. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33143. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33144. this.colors = this._mergeElement(this.colors, other.colors);
  33145. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33146. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33147. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33148. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33149. return this;
  33150. };
  33151. VertexData.prototype._mergeElement = function (source, other) {
  33152. if (!source) {
  33153. return other;
  33154. }
  33155. if (!other) {
  33156. return source;
  33157. }
  33158. var len = other.length + source.length;
  33159. var isSrcTypedArray = source instanceof Float32Array;
  33160. var isOthTypedArray = other instanceof Float32Array;
  33161. // use non-loop method when the source is Float32Array
  33162. if (isSrcTypedArray) {
  33163. var ret32 = new Float32Array(len);
  33164. ret32.set(source);
  33165. ret32.set(other, source.length);
  33166. return ret32;
  33167. // source is number[], when other is also use concat
  33168. }
  33169. else if (!isOthTypedArray) {
  33170. return source.concat(other);
  33171. // source is a number[], but other is a Float32Array, loop required
  33172. }
  33173. else {
  33174. var ret = source.slice(0); // copy source to a separate array
  33175. for (var i = 0, len = other.length; i < len; i++) {
  33176. ret.push(other[i]);
  33177. }
  33178. return ret;
  33179. }
  33180. };
  33181. VertexData.prototype._validate = function () {
  33182. if (!this.positions) {
  33183. throw new Error("Positions are required");
  33184. }
  33185. var getElementCount = function (kind, values) {
  33186. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  33187. if ((values.length % stride) !== 0) {
  33188. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  33189. }
  33190. return values.length / stride;
  33191. };
  33192. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  33193. var validateElementCount = function (kind, values) {
  33194. var elementCount = getElementCount(kind, values);
  33195. if (elementCount !== positionsElementCount) {
  33196. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  33197. }
  33198. };
  33199. if (this.normals)
  33200. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  33201. if (this.tangents)
  33202. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  33203. if (this.uvs)
  33204. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  33205. if (this.uvs2)
  33206. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  33207. if (this.uvs3)
  33208. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  33209. if (this.uvs4)
  33210. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  33211. if (this.uvs5)
  33212. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  33213. if (this.uvs6)
  33214. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  33215. if (this.colors)
  33216. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  33217. if (this.matricesIndices)
  33218. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  33219. if (this.matricesWeights)
  33220. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  33221. if (this.matricesIndicesExtra)
  33222. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  33223. if (this.matricesWeightsExtra)
  33224. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  33225. };
  33226. /**
  33227. * Serializes the VertexData.
  33228. * Returns a serialized object.
  33229. */
  33230. VertexData.prototype.serialize = function () {
  33231. var serializationObject = this.serialize();
  33232. if (this.positions) {
  33233. serializationObject.positions = this.positions;
  33234. }
  33235. if (this.normals) {
  33236. serializationObject.normals = this.normals;
  33237. }
  33238. if (this.tangents) {
  33239. serializationObject.tangents = this.tangents;
  33240. }
  33241. if (this.uvs) {
  33242. serializationObject.uvs = this.uvs;
  33243. }
  33244. if (this.uvs2) {
  33245. serializationObject.uvs2 = this.uvs2;
  33246. }
  33247. if (this.uvs3) {
  33248. serializationObject.uvs3 = this.uvs3;
  33249. }
  33250. if (this.uvs4) {
  33251. serializationObject.uvs4 = this.uvs4;
  33252. }
  33253. if (this.uvs5) {
  33254. serializationObject.uvs5 = this.uvs5;
  33255. }
  33256. if (this.uvs6) {
  33257. serializationObject.uvs6 = this.uvs6;
  33258. }
  33259. if (this.colors) {
  33260. serializationObject.colors = this.colors;
  33261. }
  33262. if (this.matricesIndices) {
  33263. serializationObject.matricesIndices = this.matricesIndices;
  33264. serializationObject.matricesIndices._isExpanded = true;
  33265. }
  33266. if (this.matricesWeights) {
  33267. serializationObject.matricesWeights = this.matricesWeights;
  33268. }
  33269. if (this.matricesIndicesExtra) {
  33270. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33271. serializationObject.matricesIndicesExtra._isExpanded = true;
  33272. }
  33273. if (this.matricesWeightsExtra) {
  33274. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33275. }
  33276. serializationObject.indices = this.indices;
  33277. return serializationObject;
  33278. };
  33279. // Statics
  33280. /**
  33281. * Returns the object VertexData associated to the passed mesh.
  33282. */
  33283. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  33284. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  33285. };
  33286. /**
  33287. * Returns the object VertexData associated to the passed geometry.
  33288. */
  33289. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  33290. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  33291. };
  33292. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  33293. var result = new VertexData();
  33294. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33295. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  33296. }
  33297. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33298. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  33299. }
  33300. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33301. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  33302. }
  33303. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33304. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  33305. }
  33306. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33307. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  33308. }
  33309. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33310. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  33311. }
  33312. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33313. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  33314. }
  33315. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33316. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  33317. }
  33318. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33319. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  33320. }
  33321. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33322. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  33323. }
  33324. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33325. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  33326. }
  33327. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33328. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  33329. }
  33330. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33331. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  33332. }
  33333. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33334. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  33335. }
  33336. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33337. return result;
  33338. };
  33339. /**
  33340. * Creates the vertexData of the Ribbon.
  33341. */
  33342. VertexData.CreateRibbon = function (options) {
  33343. var pathArray = options.pathArray;
  33344. var closeArray = options.closeArray || false;
  33345. var closePath = options.closePath || false;
  33346. var invertUV = options.invertUV || false;
  33347. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33348. var offset = options.offset || defaultOffset;
  33349. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33350. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33351. var customUV = options.uvs;
  33352. var customColors = options.colors;
  33353. var positions = [];
  33354. var indices = [];
  33355. var normals = [];
  33356. var uvs = [];
  33357. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33358. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33359. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33360. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33361. var minlg; // minimal length among all paths from pathArray
  33362. var lg = []; // array of path lengths : nb of vertex per path
  33363. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33364. var p; // path iterator
  33365. var i; // point iterator
  33366. var j; // point iterator
  33367. // if single path in pathArray
  33368. if (pathArray.length < 2) {
  33369. var ar1 = [];
  33370. var ar2 = [];
  33371. for (i = 0; i < pathArray[0].length - offset; i++) {
  33372. ar1.push(pathArray[0][i]);
  33373. ar2.push(pathArray[0][i + offset]);
  33374. }
  33375. pathArray = [ar1, ar2];
  33376. }
  33377. // positions and horizontal distances (u)
  33378. var idc = 0;
  33379. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  33380. var path;
  33381. var l;
  33382. minlg = pathArray[0].length;
  33383. var vectlg;
  33384. var dist;
  33385. for (p = 0; p < pathArray.length; p++) {
  33386. uTotalDistance[p] = 0;
  33387. us[p] = [0];
  33388. path = pathArray[p];
  33389. l = path.length;
  33390. minlg = (minlg < l) ? minlg : l;
  33391. j = 0;
  33392. while (j < l) {
  33393. positions.push(path[j].x, path[j].y, path[j].z);
  33394. if (j > 0) {
  33395. vectlg = path[j].subtract(path[j - 1]).length();
  33396. dist = vectlg + uTotalDistance[p];
  33397. us[p].push(dist);
  33398. uTotalDistance[p] = dist;
  33399. }
  33400. j++;
  33401. }
  33402. if (closePath) {
  33403. j--;
  33404. positions.push(path[0].x, path[0].y, path[0].z);
  33405. vectlg = path[j].subtract(path[0]).length();
  33406. dist = vectlg + uTotalDistance[p];
  33407. us[p].push(dist);
  33408. uTotalDistance[p] = dist;
  33409. }
  33410. lg[p] = l + closePathCorr;
  33411. idx[p] = idc;
  33412. idc += (l + closePathCorr);
  33413. }
  33414. // vertical distances (v)
  33415. var path1;
  33416. var path2;
  33417. var vertex1 = null;
  33418. var vertex2 = null;
  33419. for (i = 0; i < minlg + closePathCorr; i++) {
  33420. vTotalDistance[i] = 0;
  33421. vs[i] = [0];
  33422. for (p = 0; p < pathArray.length - 1; p++) {
  33423. path1 = pathArray[p];
  33424. path2 = pathArray[p + 1];
  33425. if (i === minlg) {
  33426. vertex1 = path1[0];
  33427. vertex2 = path2[0];
  33428. }
  33429. else {
  33430. vertex1 = path1[i];
  33431. vertex2 = path2[i];
  33432. }
  33433. vectlg = vertex2.subtract(vertex1).length();
  33434. dist = vectlg + vTotalDistance[i];
  33435. vs[i].push(dist);
  33436. vTotalDistance[i] = dist;
  33437. }
  33438. if (closeArray && vertex2 && vertex1) {
  33439. path1 = pathArray[p];
  33440. path2 = pathArray[0];
  33441. if (i === minlg) {
  33442. vertex2 = path2[0];
  33443. }
  33444. vectlg = vertex2.subtract(vertex1).length();
  33445. dist = vectlg + vTotalDistance[i];
  33446. vTotalDistance[i] = dist;
  33447. }
  33448. }
  33449. // uvs
  33450. var u;
  33451. var v;
  33452. if (customUV) {
  33453. for (p = 0; p < customUV.length; p++) {
  33454. uvs.push(customUV[p].x, customUV[p].y);
  33455. }
  33456. }
  33457. else {
  33458. for (p = 0; p < pathArray.length; p++) {
  33459. for (i = 0; i < minlg + closePathCorr; i++) {
  33460. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33461. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33462. if (invertUV) {
  33463. uvs.push(v, u);
  33464. }
  33465. else {
  33466. uvs.push(u, v);
  33467. }
  33468. }
  33469. }
  33470. }
  33471. // indices
  33472. p = 0; // path index
  33473. var pi = 0; // positions array index
  33474. var l1 = lg[p] - 1; // path1 length
  33475. var l2 = lg[p + 1] - 1; // path2 length
  33476. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33477. var shft = idx[1] - idx[0]; // shift
  33478. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33479. while (pi <= min && p < path1nb) {
  33480. // 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
  33481. indices.push(pi, pi + shft, pi + 1);
  33482. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33483. pi += 1;
  33484. if (pi === min) {
  33485. p++;
  33486. if (p === lg.length - 1) {
  33487. shft = idx[0] - idx[p];
  33488. l1 = lg[p] - 1;
  33489. l2 = lg[0] - 1;
  33490. }
  33491. else {
  33492. shft = idx[p + 1] - idx[p];
  33493. l1 = lg[p] - 1;
  33494. l2 = lg[p + 1] - 1;
  33495. }
  33496. pi = idx[p];
  33497. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33498. }
  33499. }
  33500. // normals
  33501. VertexData.ComputeNormals(positions, indices, normals);
  33502. if (closePath) {
  33503. var indexFirst = 0;
  33504. var indexLast = 0;
  33505. for (p = 0; p < pathArray.length; p++) {
  33506. indexFirst = idx[p] * 3;
  33507. if (p + 1 < pathArray.length) {
  33508. indexLast = (idx[p + 1] - 1) * 3;
  33509. }
  33510. else {
  33511. indexLast = normals.length - 3;
  33512. }
  33513. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33514. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33515. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33516. normals[indexLast] = normals[indexFirst];
  33517. normals[indexLast + 1] = normals[indexFirst + 1];
  33518. normals[indexLast + 2] = normals[indexFirst + 2];
  33519. }
  33520. }
  33521. // sides
  33522. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33523. // Colors
  33524. var colors = null;
  33525. if (customColors) {
  33526. colors = new Float32Array(customColors.length * 4);
  33527. for (var c = 0; c < customColors.length; c++) {
  33528. colors[c * 4] = customColors[c].r;
  33529. colors[c * 4 + 1] = customColors[c].g;
  33530. colors[c * 4 + 2] = customColors[c].b;
  33531. colors[c * 4 + 3] = customColors[c].a;
  33532. }
  33533. }
  33534. // Result
  33535. var vertexData = new VertexData();
  33536. var positions32 = new Float32Array(positions);
  33537. var normals32 = new Float32Array(normals);
  33538. var uvs32 = new Float32Array(uvs);
  33539. vertexData.indices = indices;
  33540. vertexData.positions = positions32;
  33541. vertexData.normals = normals32;
  33542. vertexData.uvs = uvs32;
  33543. if (colors) {
  33544. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33545. }
  33546. if (closePath) {
  33547. vertexData._idx = idx;
  33548. }
  33549. return vertexData;
  33550. };
  33551. /**
  33552. * Creates the VertexData of the Box.
  33553. */
  33554. VertexData.CreateBox = function (options) {
  33555. var normalsSource = [
  33556. new BABYLON.Vector3(0, 0, 1),
  33557. new BABYLON.Vector3(0, 0, -1),
  33558. new BABYLON.Vector3(1, 0, 0),
  33559. new BABYLON.Vector3(-1, 0, 0),
  33560. new BABYLON.Vector3(0, 1, 0),
  33561. new BABYLON.Vector3(0, -1, 0)
  33562. ];
  33563. var indices = [];
  33564. var positions = [];
  33565. var normals = [];
  33566. var uvs = [];
  33567. var width = options.width || options.size || 1;
  33568. var height = options.height || options.size || 1;
  33569. var depth = options.depth || options.size || 1;
  33570. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33571. var faceUV = options.faceUV || new Array(6);
  33572. var faceColors = options.faceColors;
  33573. var colors = [];
  33574. // default face colors and UV if undefined
  33575. for (var f = 0; f < 6; f++) {
  33576. if (faceUV[f] === undefined) {
  33577. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33578. }
  33579. if (faceColors && faceColors[f] === undefined) {
  33580. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33581. }
  33582. }
  33583. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33584. // Create each face in turn.
  33585. for (var index = 0; index < normalsSource.length; index++) {
  33586. var normal = normalsSource[index];
  33587. // Get two vectors perpendicular to the face normal and to each other.
  33588. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33589. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33590. // Six indices (two triangles) per face.
  33591. var verticesLength = positions.length / 3;
  33592. indices.push(verticesLength);
  33593. indices.push(verticesLength + 1);
  33594. indices.push(verticesLength + 2);
  33595. indices.push(verticesLength);
  33596. indices.push(verticesLength + 2);
  33597. indices.push(verticesLength + 3);
  33598. // Four vertices per face.
  33599. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33600. positions.push(vertex.x, vertex.y, vertex.z);
  33601. normals.push(normal.x, normal.y, normal.z);
  33602. uvs.push(faceUV[index].z, faceUV[index].w);
  33603. if (faceColors) {
  33604. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33605. }
  33606. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33607. positions.push(vertex.x, vertex.y, vertex.z);
  33608. normals.push(normal.x, normal.y, normal.z);
  33609. uvs.push(faceUV[index].x, faceUV[index].w);
  33610. if (faceColors) {
  33611. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33612. }
  33613. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33614. positions.push(vertex.x, vertex.y, vertex.z);
  33615. normals.push(normal.x, normal.y, normal.z);
  33616. uvs.push(faceUV[index].x, faceUV[index].y);
  33617. if (faceColors) {
  33618. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33619. }
  33620. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33621. positions.push(vertex.x, vertex.y, vertex.z);
  33622. normals.push(normal.x, normal.y, normal.z);
  33623. uvs.push(faceUV[index].z, faceUV[index].y);
  33624. if (faceColors) {
  33625. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33626. }
  33627. }
  33628. // sides
  33629. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33630. // Result
  33631. var vertexData = new VertexData();
  33632. vertexData.indices = indices;
  33633. vertexData.positions = positions;
  33634. vertexData.normals = normals;
  33635. vertexData.uvs = uvs;
  33636. if (faceColors) {
  33637. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33638. vertexData.colors = totalColors;
  33639. }
  33640. return vertexData;
  33641. };
  33642. /**
  33643. * Creates the VertexData of the Sphere.
  33644. */
  33645. VertexData.CreateSphere = function (options) {
  33646. var segments = options.segments || 32;
  33647. var diameterX = options.diameterX || options.diameter || 1;
  33648. var diameterY = options.diameterY || options.diameter || 1;
  33649. var diameterZ = options.diameterZ || options.diameter || 1;
  33650. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33651. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33652. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33653. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33654. var totalZRotationSteps = 2 + segments;
  33655. var totalYRotationSteps = 2 * totalZRotationSteps;
  33656. var indices = [];
  33657. var positions = [];
  33658. var normals = [];
  33659. var uvs = [];
  33660. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33661. var normalizedZ = zRotationStep / totalZRotationSteps;
  33662. var angleZ = normalizedZ * Math.PI * slice;
  33663. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33664. var normalizedY = yRotationStep / totalYRotationSteps;
  33665. var angleY = normalizedY * Math.PI * 2 * arc;
  33666. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33667. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33668. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33669. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33670. var vertex = complete.multiply(radius);
  33671. var normal = complete.divide(radius).normalize();
  33672. positions.push(vertex.x, vertex.y, vertex.z);
  33673. normals.push(normal.x, normal.y, normal.z);
  33674. uvs.push(normalizedY, normalizedZ);
  33675. }
  33676. if (zRotationStep > 0) {
  33677. var verticesCount = positions.length / 3;
  33678. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33679. indices.push((firstIndex));
  33680. indices.push((firstIndex + 1));
  33681. indices.push(firstIndex + totalYRotationSteps + 1);
  33682. indices.push((firstIndex + totalYRotationSteps + 1));
  33683. indices.push((firstIndex + 1));
  33684. indices.push((firstIndex + totalYRotationSteps + 2));
  33685. }
  33686. }
  33687. }
  33688. // Sides
  33689. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33690. // Result
  33691. var vertexData = new VertexData();
  33692. vertexData.indices = indices;
  33693. vertexData.positions = positions;
  33694. vertexData.normals = normals;
  33695. vertexData.uvs = uvs;
  33696. return vertexData;
  33697. };
  33698. /**
  33699. * Creates the VertexData of the Cylinder or Cone.
  33700. */
  33701. VertexData.CreateCylinder = function (options) {
  33702. var height = options.height || 2;
  33703. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33704. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33705. var tessellation = options.tessellation || 24;
  33706. var subdivisions = options.subdivisions || 1;
  33707. var hasRings = options.hasRings ? true : false;
  33708. var enclose = options.enclose ? true : false;
  33709. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33710. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33711. var faceUV = options.faceUV || new Array(3);
  33712. var faceColors = options.faceColors;
  33713. // default face colors and UV if undefined
  33714. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33715. var ringNb = (hasRings) ? subdivisions : 1;
  33716. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33717. var f;
  33718. for (f = 0; f < surfaceNb; f++) {
  33719. if (faceColors && faceColors[f] === undefined) {
  33720. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33721. }
  33722. }
  33723. for (f = 0; f < surfaceNb; f++) {
  33724. if (faceUV && faceUV[f] === undefined) {
  33725. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33726. }
  33727. }
  33728. var indices = new Array();
  33729. var positions = new Array();
  33730. var normals = new Array();
  33731. var uvs = new Array();
  33732. var colors = new Array();
  33733. var angle_step = Math.PI * 2 * arc / tessellation;
  33734. var angle;
  33735. var h;
  33736. var radius;
  33737. var tan = (diameterBottom - diameterTop) / 2 / height;
  33738. var ringVertex = BABYLON.Vector3.Zero();
  33739. var ringNormal = BABYLON.Vector3.Zero();
  33740. var ringFirstVertex = BABYLON.Vector3.Zero();
  33741. var ringFirstNormal = BABYLON.Vector3.Zero();
  33742. var quadNormal = BABYLON.Vector3.Zero();
  33743. var Y = BABYLON.Axis.Y;
  33744. // positions, normals, uvs
  33745. var i;
  33746. var j;
  33747. var r;
  33748. var ringIdx = 1;
  33749. var s = 1; // surface index
  33750. var cs = 0;
  33751. var v = 0;
  33752. for (i = 0; i <= subdivisions; i++) {
  33753. h = i / subdivisions;
  33754. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33755. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33756. for (r = 0; r < ringIdx; r++) {
  33757. if (hasRings) {
  33758. s += r;
  33759. }
  33760. if (enclose) {
  33761. s += 2 * r;
  33762. }
  33763. for (j = 0; j <= tessellation; j++) {
  33764. angle = j * angle_step;
  33765. // position
  33766. ringVertex.x = Math.cos(-angle) * radius;
  33767. ringVertex.y = -height / 2 + h * height;
  33768. ringVertex.z = Math.sin(-angle) * radius;
  33769. // normal
  33770. if (diameterTop === 0 && i === subdivisions) {
  33771. // if no top cap, reuse former normals
  33772. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33773. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33774. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33775. }
  33776. else {
  33777. ringNormal.x = ringVertex.x;
  33778. ringNormal.z = ringVertex.z;
  33779. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33780. ringNormal.normalize();
  33781. }
  33782. // keep first ring vertex values for enclose
  33783. if (j === 0) {
  33784. ringFirstVertex.copyFrom(ringVertex);
  33785. ringFirstNormal.copyFrom(ringNormal);
  33786. }
  33787. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33788. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33789. if (hasRings) {
  33790. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33791. }
  33792. else {
  33793. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33794. }
  33795. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33796. if (faceColors) {
  33797. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33798. }
  33799. }
  33800. // if enclose, add four vertices and their dedicated normals
  33801. if (arc !== 1 && enclose) {
  33802. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33803. positions.push(0, ringVertex.y, 0);
  33804. positions.push(0, ringVertex.y, 0);
  33805. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33806. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33807. quadNormal.normalize();
  33808. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33809. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33810. quadNormal.normalize();
  33811. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33812. if (hasRings) {
  33813. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33814. }
  33815. else {
  33816. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33817. }
  33818. uvs.push(faceUV[s + 1].x, v);
  33819. uvs.push(faceUV[s + 1].z, v);
  33820. if (hasRings) {
  33821. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33822. }
  33823. else {
  33824. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33825. }
  33826. uvs.push(faceUV[s + 2].x, v);
  33827. uvs.push(faceUV[s + 2].z, v);
  33828. if (faceColors) {
  33829. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33830. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33831. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33832. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33833. }
  33834. }
  33835. if (cs !== s) {
  33836. cs = s;
  33837. }
  33838. }
  33839. }
  33840. // indices
  33841. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33842. var s;
  33843. i = 0;
  33844. for (s = 0; s < subdivisions; s++) {
  33845. var i0 = 0;
  33846. var i1 = 0;
  33847. var i2 = 0;
  33848. var i3 = 0;
  33849. for (j = 0; j < tessellation; j++) {
  33850. i0 = i * (e + 1) + j;
  33851. i1 = (i + 1) * (e + 1) + j;
  33852. i2 = i * (e + 1) + (j + 1);
  33853. i3 = (i + 1) * (e + 1) + (j + 1);
  33854. indices.push(i0, i1, i2);
  33855. indices.push(i3, i2, i1);
  33856. }
  33857. if (arc !== 1 && enclose) {
  33858. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33859. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33860. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33861. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33862. }
  33863. i = (hasRings) ? (i + 2) : (i + 1);
  33864. }
  33865. // Caps
  33866. var createCylinderCap = function (isTop) {
  33867. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33868. if (radius === 0) {
  33869. return;
  33870. }
  33871. // Cap positions, normals & uvs
  33872. var angle;
  33873. var circleVector;
  33874. var i;
  33875. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33876. var c = null;
  33877. if (faceColors) {
  33878. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33879. }
  33880. // cap center
  33881. var vbase = positions.length / 3;
  33882. var offset = isTop ? height / 2 : -height / 2;
  33883. var center = new BABYLON.Vector3(0, offset, 0);
  33884. positions.push(center.x, center.y, center.z);
  33885. normals.push(0, isTop ? 1 : -1, 0);
  33886. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33887. if (c) {
  33888. colors.push(c.r, c.g, c.b, c.a);
  33889. }
  33890. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33891. for (i = 0; i <= tessellation; i++) {
  33892. angle = Math.PI * 2 * i * arc / tessellation;
  33893. var cos = Math.cos(-angle);
  33894. var sin = Math.sin(-angle);
  33895. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33896. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33897. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33898. normals.push(0, isTop ? 1 : -1, 0);
  33899. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33900. if (c) {
  33901. colors.push(c.r, c.g, c.b, c.a);
  33902. }
  33903. }
  33904. // Cap indices
  33905. for (i = 0; i < tessellation; i++) {
  33906. if (!isTop) {
  33907. indices.push(vbase);
  33908. indices.push(vbase + (i + 1));
  33909. indices.push(vbase + (i + 2));
  33910. }
  33911. else {
  33912. indices.push(vbase);
  33913. indices.push(vbase + (i + 2));
  33914. indices.push(vbase + (i + 1));
  33915. }
  33916. }
  33917. };
  33918. // add caps to geometry
  33919. createCylinderCap(false);
  33920. createCylinderCap(true);
  33921. // Sides
  33922. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33923. var vertexData = new VertexData();
  33924. vertexData.indices = indices;
  33925. vertexData.positions = positions;
  33926. vertexData.normals = normals;
  33927. vertexData.uvs = uvs;
  33928. if (faceColors) {
  33929. vertexData.colors = colors;
  33930. }
  33931. return vertexData;
  33932. };
  33933. /**
  33934. * Creates the VertexData of the Torus.
  33935. */
  33936. VertexData.CreateTorus = function (options) {
  33937. var indices = [];
  33938. var positions = [];
  33939. var normals = [];
  33940. var uvs = [];
  33941. var diameter = options.diameter || 1;
  33942. var thickness = options.thickness || 0.5;
  33943. var tessellation = options.tessellation || 16;
  33944. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33945. var stride = tessellation + 1;
  33946. for (var i = 0; i <= tessellation; i++) {
  33947. var u = i / tessellation;
  33948. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33949. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33950. for (var j = 0; j <= tessellation; j++) {
  33951. var v = 1 - j / tessellation;
  33952. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33953. var dx = Math.cos(innerAngle);
  33954. var dy = Math.sin(innerAngle);
  33955. // Create a vertex.
  33956. var normal = new BABYLON.Vector3(dx, dy, 0);
  33957. var position = normal.scale(thickness / 2);
  33958. var textureCoordinate = new BABYLON.Vector2(u, v);
  33959. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33960. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33961. positions.push(position.x, position.y, position.z);
  33962. normals.push(normal.x, normal.y, normal.z);
  33963. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33964. // And create indices for two triangles.
  33965. var nextI = (i + 1) % stride;
  33966. var nextJ = (j + 1) % stride;
  33967. indices.push(i * stride + j);
  33968. indices.push(i * stride + nextJ);
  33969. indices.push(nextI * stride + j);
  33970. indices.push(i * stride + nextJ);
  33971. indices.push(nextI * stride + nextJ);
  33972. indices.push(nextI * stride + j);
  33973. }
  33974. }
  33975. // Sides
  33976. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33977. // Result
  33978. var vertexData = new VertexData();
  33979. vertexData.indices = indices;
  33980. vertexData.positions = positions;
  33981. vertexData.normals = normals;
  33982. vertexData.uvs = uvs;
  33983. return vertexData;
  33984. };
  33985. /**
  33986. * Creates the VertexData of the LineSystem.
  33987. */
  33988. VertexData.CreateLineSystem = function (options) {
  33989. var indices = [];
  33990. var positions = [];
  33991. var lines = options.lines;
  33992. var colors = options.colors;
  33993. var vertexColors = [];
  33994. var idx = 0;
  33995. for (var l = 0; l < lines.length; l++) {
  33996. var points = lines[l];
  33997. for (var index = 0; index < points.length; index++) {
  33998. positions.push(points[index].x, points[index].y, points[index].z);
  33999. if (colors) {
  34000. var color = colors[l];
  34001. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  34002. }
  34003. if (index > 0) {
  34004. indices.push(idx - 1);
  34005. indices.push(idx);
  34006. }
  34007. idx++;
  34008. }
  34009. }
  34010. var vertexData = new VertexData();
  34011. vertexData.indices = indices;
  34012. vertexData.positions = positions;
  34013. if (colors) {
  34014. vertexData.colors = vertexColors;
  34015. }
  34016. return vertexData;
  34017. };
  34018. /**
  34019. * Create the VertexData of the DashedLines.
  34020. */
  34021. VertexData.CreateDashedLines = function (options) {
  34022. var dashSize = options.dashSize || 3;
  34023. var gapSize = options.gapSize || 1;
  34024. var dashNb = options.dashNb || 200;
  34025. var points = options.points;
  34026. var positions = new Array();
  34027. var indices = new Array();
  34028. var curvect = BABYLON.Vector3.Zero();
  34029. var lg = 0;
  34030. var nb = 0;
  34031. var shft = 0;
  34032. var dashshft = 0;
  34033. var curshft = 0;
  34034. var idx = 0;
  34035. var i = 0;
  34036. for (i = 0; i < points.length - 1; i++) {
  34037. points[i + 1].subtractToRef(points[i], curvect);
  34038. lg += curvect.length();
  34039. }
  34040. shft = lg / dashNb;
  34041. dashshft = dashSize * shft / (dashSize + gapSize);
  34042. for (i = 0; i < points.length - 1; i++) {
  34043. points[i + 1].subtractToRef(points[i], curvect);
  34044. nb = Math.floor(curvect.length() / shft);
  34045. curvect.normalize();
  34046. for (var j = 0; j < nb; j++) {
  34047. curshft = shft * j;
  34048. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  34049. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  34050. indices.push(idx, idx + 1);
  34051. idx += 2;
  34052. }
  34053. }
  34054. // Result
  34055. var vertexData = new VertexData();
  34056. vertexData.positions = positions;
  34057. vertexData.indices = indices;
  34058. return vertexData;
  34059. };
  34060. /**
  34061. * Creates the VertexData of the Ground.
  34062. */
  34063. VertexData.CreateGround = function (options) {
  34064. var indices = [];
  34065. var positions = [];
  34066. var normals = [];
  34067. var uvs = [];
  34068. var row, col;
  34069. var width = options.width || 1;
  34070. var height = options.height || 1;
  34071. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34072. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34073. for (row = 0; row <= subdivisionsY; row++) {
  34074. for (col = 0; col <= subdivisionsX; col++) {
  34075. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34076. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34077. positions.push(position.x, position.y, position.z);
  34078. normals.push(normal.x, normal.y, normal.z);
  34079. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34080. }
  34081. }
  34082. for (row = 0; row < subdivisionsY; row++) {
  34083. for (col = 0; col < subdivisionsX; col++) {
  34084. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34085. indices.push(col + 1 + row * (subdivisionsX + 1));
  34086. indices.push(col + row * (subdivisionsX + 1));
  34087. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34088. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34089. indices.push(col + row * (subdivisionsX + 1));
  34090. }
  34091. }
  34092. // Result
  34093. var vertexData = new VertexData();
  34094. vertexData.indices = indices;
  34095. vertexData.positions = positions;
  34096. vertexData.normals = normals;
  34097. vertexData.uvs = uvs;
  34098. return vertexData;
  34099. };
  34100. /**
  34101. * Creates the VertexData of the TiledGround.
  34102. */
  34103. VertexData.CreateTiledGround = function (options) {
  34104. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  34105. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  34106. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  34107. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  34108. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34109. var precision = options.precision || { w: 1, h: 1 };
  34110. var indices = new Array();
  34111. var positions = new Array();
  34112. var normals = new Array();
  34113. var uvs = new Array();
  34114. var row, col, tileRow, tileCol;
  34115. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34116. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34117. precision.w = (precision.w < 1) ? 1 : precision.w;
  34118. precision.h = (precision.h < 1) ? 1 : precision.h;
  34119. var tileSize = {
  34120. 'w': (xmax - xmin) / subdivisions.w,
  34121. 'h': (zmax - zmin) / subdivisions.h
  34122. };
  34123. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34124. // Indices
  34125. var base = positions.length / 3;
  34126. var rowLength = precision.w + 1;
  34127. for (row = 0; row < precision.h; row++) {
  34128. for (col = 0; col < precision.w; col++) {
  34129. var square = [
  34130. base + col + row * rowLength,
  34131. base + (col + 1) + row * rowLength,
  34132. base + (col + 1) + (row + 1) * rowLength,
  34133. base + col + (row + 1) * rowLength
  34134. ];
  34135. indices.push(square[1]);
  34136. indices.push(square[2]);
  34137. indices.push(square[3]);
  34138. indices.push(square[0]);
  34139. indices.push(square[1]);
  34140. indices.push(square[3]);
  34141. }
  34142. }
  34143. // Position, normals and uvs
  34144. var position = BABYLON.Vector3.Zero();
  34145. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34146. for (row = 0; row <= precision.h; row++) {
  34147. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34148. for (col = 0; col <= precision.w; col++) {
  34149. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34150. position.y = 0;
  34151. positions.push(position.x, position.y, position.z);
  34152. normals.push(normal.x, normal.y, normal.z);
  34153. uvs.push(col / precision.w, row / precision.h);
  34154. }
  34155. }
  34156. }
  34157. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34158. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34159. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34160. }
  34161. }
  34162. // Result
  34163. var vertexData = new VertexData();
  34164. vertexData.indices = indices;
  34165. vertexData.positions = positions;
  34166. vertexData.normals = normals;
  34167. vertexData.uvs = uvs;
  34168. return vertexData;
  34169. };
  34170. /**
  34171. * Creates the VertexData of the Ground designed from a heightmap.
  34172. */
  34173. VertexData.CreateGroundFromHeightMap = function (options) {
  34174. var indices = [];
  34175. var positions = [];
  34176. var normals = [];
  34177. var uvs = [];
  34178. var row, col;
  34179. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  34180. // Vertices
  34181. for (row = 0; row <= options.subdivisions; row++) {
  34182. for (col = 0; col <= options.subdivisions; col++) {
  34183. 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));
  34184. // Compute height
  34185. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34186. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34187. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34188. var r = options.buffer[pos] / 255.0;
  34189. var g = options.buffer[pos + 1] / 255.0;
  34190. var b = options.buffer[pos + 2] / 255.0;
  34191. var gradient = r * filter.r + g * filter.g + b * filter.b;
  34192. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34193. // Add vertex
  34194. positions.push(position.x, position.y, position.z);
  34195. normals.push(0, 0, 0);
  34196. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34197. }
  34198. }
  34199. // Indices
  34200. for (row = 0; row < options.subdivisions; row++) {
  34201. for (col = 0; col < options.subdivisions; col++) {
  34202. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34203. indices.push(col + 1 + row * (options.subdivisions + 1));
  34204. indices.push(col + row * (options.subdivisions + 1));
  34205. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34206. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34207. indices.push(col + row * (options.subdivisions + 1));
  34208. }
  34209. }
  34210. // Normals
  34211. VertexData.ComputeNormals(positions, indices, normals);
  34212. // Result
  34213. var vertexData = new VertexData();
  34214. vertexData.indices = indices;
  34215. vertexData.positions = positions;
  34216. vertexData.normals = normals;
  34217. vertexData.uvs = uvs;
  34218. return vertexData;
  34219. };
  34220. /**
  34221. * Creates the VertexData of the Plane.
  34222. */
  34223. VertexData.CreatePlane = function (options) {
  34224. var indices = [];
  34225. var positions = [];
  34226. var normals = [];
  34227. var uvs = [];
  34228. var width = options.width || options.size || 1;
  34229. var height = options.height || options.size || 1;
  34230. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34231. // Vertices
  34232. var halfWidth = width / 2.0;
  34233. var halfHeight = height / 2.0;
  34234. positions.push(-halfWidth, -halfHeight, 0);
  34235. normals.push(0, 0, -1.0);
  34236. uvs.push(0.0, 0.0);
  34237. positions.push(halfWidth, -halfHeight, 0);
  34238. normals.push(0, 0, -1.0);
  34239. uvs.push(1.0, 0.0);
  34240. positions.push(halfWidth, halfHeight, 0);
  34241. normals.push(0, 0, -1.0);
  34242. uvs.push(1.0, 1.0);
  34243. positions.push(-halfWidth, halfHeight, 0);
  34244. normals.push(0, 0, -1.0);
  34245. uvs.push(0.0, 1.0);
  34246. // Indices
  34247. indices.push(0);
  34248. indices.push(1);
  34249. indices.push(2);
  34250. indices.push(0);
  34251. indices.push(2);
  34252. indices.push(3);
  34253. // Sides
  34254. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34255. // Result
  34256. var vertexData = new VertexData();
  34257. vertexData.indices = indices;
  34258. vertexData.positions = positions;
  34259. vertexData.normals = normals;
  34260. vertexData.uvs = uvs;
  34261. return vertexData;
  34262. };
  34263. /**
  34264. * Creates the VertexData of the Disc or regular Polygon.
  34265. */
  34266. VertexData.CreateDisc = function (options) {
  34267. var positions = new Array();
  34268. var indices = new Array();
  34269. var normals = new Array();
  34270. var uvs = new Array();
  34271. var radius = options.radius || 0.5;
  34272. var tessellation = options.tessellation || 64;
  34273. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34274. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34275. // positions and uvs
  34276. positions.push(0, 0, 0); // disc center first
  34277. uvs.push(0.5, 0.5);
  34278. var theta = Math.PI * 2 * arc;
  34279. var step = theta / tessellation;
  34280. for (var a = 0; a < theta; a += step) {
  34281. var x = Math.cos(a);
  34282. var y = Math.sin(a);
  34283. var u = (x + 1) / 2;
  34284. var v = (1 - y) / 2;
  34285. positions.push(radius * x, radius * y, 0);
  34286. uvs.push(u, v);
  34287. }
  34288. if (arc === 1) {
  34289. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34290. uvs.push(uvs[2], uvs[3]);
  34291. }
  34292. //indices
  34293. var vertexNb = positions.length / 3;
  34294. for (var i = 1; i < vertexNb - 1; i++) {
  34295. indices.push(i + 1, 0, i);
  34296. }
  34297. // result
  34298. VertexData.ComputeNormals(positions, indices, normals);
  34299. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34300. var vertexData = new VertexData();
  34301. vertexData.indices = indices;
  34302. vertexData.positions = positions;
  34303. vertexData.normals = normals;
  34304. vertexData.uvs = uvs;
  34305. return vertexData;
  34306. };
  34307. /**
  34308. * Re-creates the VertexData of the Polygon for sideOrientation.
  34309. */
  34310. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  34311. var faceUV = fUV || new Array(3);
  34312. var faceColors = fColors;
  34313. var colors = [];
  34314. // default face colors and UV if undefined
  34315. for (var f = 0; f < 3; f++) {
  34316. if (faceUV[f] === undefined) {
  34317. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34318. }
  34319. if (faceColors && faceColors[f] === undefined) {
  34320. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34321. }
  34322. }
  34323. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34324. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34325. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34326. var indices = polygon.getIndices();
  34327. // set face colours and textures
  34328. var idx = 0;
  34329. var face = 0;
  34330. for (var index = 0; index < normals.length; index += 3) {
  34331. //Edge Face no. 1
  34332. if (Math.abs(normals[index + 1]) < 0.001) {
  34333. face = 1;
  34334. }
  34335. //Top Face no. 0
  34336. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  34337. face = 0;
  34338. }
  34339. //Bottom Face no. 2
  34340. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  34341. face = 2;
  34342. }
  34343. idx = index / 3;
  34344. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  34345. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  34346. if (faceColors) {
  34347. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  34348. }
  34349. }
  34350. // sides
  34351. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  34352. // Result
  34353. var vertexData = new VertexData();
  34354. vertexData.indices = indices;
  34355. vertexData.positions = positions;
  34356. vertexData.normals = normals;
  34357. vertexData.uvs = uvs;
  34358. if (faceColors) {
  34359. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34360. vertexData.colors = totalColors;
  34361. }
  34362. return vertexData;
  34363. };
  34364. /**
  34365. * Creates the VertexData of the IcoSphere.
  34366. */
  34367. VertexData.CreateIcoSphere = function (options) {
  34368. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34369. var radius = options.radius || 1;
  34370. var flat = (options.flat === undefined) ? true : options.flat;
  34371. var subdivisions = options.subdivisions || 4;
  34372. var radiusX = options.radiusX || radius;
  34373. var radiusY = options.radiusY || radius;
  34374. var radiusZ = options.radiusZ || radius;
  34375. var t = (1 + Math.sqrt(5)) / 2;
  34376. // 12 vertex x,y,z
  34377. var ico_vertices = [
  34378. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34379. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34380. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34381. ];
  34382. // index of 3 vertex makes a face of icopshere
  34383. var ico_indices = [
  34384. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34385. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34386. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34387. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34388. ];
  34389. // vertex for uv have aliased position, not for UV
  34390. var vertices_unalias_id = [
  34391. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34392. // vertex alias
  34393. 0,
  34394. 2,
  34395. 3,
  34396. 3,
  34397. 3,
  34398. 4,
  34399. 7,
  34400. 8,
  34401. 9,
  34402. 9,
  34403. 10,
  34404. 11 // 23: B + 12
  34405. ];
  34406. // uv as integer step (not pixels !)
  34407. var ico_vertexuv = [
  34408. 5, 1, 3, 1, 6, 4, 0, 0,
  34409. 5, 3, 4, 2, 2, 2, 4, 0,
  34410. 2, 0, 1, 1, 6, 0, 6, 2,
  34411. // vertex alias (for same vertex on different faces)
  34412. 0, 4,
  34413. 3, 3,
  34414. 4, 4,
  34415. 3, 1,
  34416. 4, 2,
  34417. 4, 4,
  34418. 0, 2,
  34419. 1, 1,
  34420. 2, 2,
  34421. 3, 3,
  34422. 1, 3,
  34423. 2, 4 // 23: B + 12
  34424. ];
  34425. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34426. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34427. // First island of uv mapping
  34428. // v = 4h 3+ 2
  34429. // v = 3h 9+ 4
  34430. // v = 2h 9+ 5 B
  34431. // v = 1h 9 1 0
  34432. // v = 0h 3 8 7 A
  34433. // u = 0 1 2 3 4 5 6 *a
  34434. // Second island of uv mapping
  34435. // v = 4h 0+ B+ 4+
  34436. // v = 3h A+ 2+
  34437. // v = 2h 7+ 6 3+
  34438. // v = 1h 8+ 3+
  34439. // v = 0h
  34440. // u = 0 1 2 3 4 5 6 *a
  34441. // Face layout on texture UV mapping
  34442. // ============
  34443. // \ 4 /\ 16 / ======
  34444. // \ / \ / /\ 11 /
  34445. // \/ 7 \/ / \ /
  34446. // ======= / 10 \/
  34447. // /\ 17 /\ =======
  34448. // / \ / \ \ 15 /\
  34449. // / 8 \/ 12 \ \ / \
  34450. // ============ \/ 6 \
  34451. // \ 18 /\ ============
  34452. // \ / \ \ 5 /\ 0 /
  34453. // \/ 13 \ \ / \ /
  34454. // ======= \/ 1 \/
  34455. // =============
  34456. // /\ 19 /\ 2 /\
  34457. // / \ / \ / \
  34458. // / 14 \/ 9 \/ 3 \
  34459. // ===================
  34460. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34461. var ustep = 138 / 1024;
  34462. var vstep = 239 / 1024;
  34463. var uoffset = 60 / 1024;
  34464. var voffset = 26 / 1024;
  34465. // Second island should have margin, not to touch the first island
  34466. // avoid any borderline artefact in pixel rounding
  34467. var island_u_offset = -40 / 1024;
  34468. var island_v_offset = +20 / 1024;
  34469. // face is either island 0 or 1 :
  34470. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34471. var island = [
  34472. 0, 0, 0, 0, 1,
  34473. 0, 0, 1, 1, 0,
  34474. 0, 0, 1, 1, 0,
  34475. 0, 1, 1, 1, 0 // 15 - 19
  34476. ];
  34477. var indices = new Array();
  34478. var positions = new Array();
  34479. var normals = new Array();
  34480. var uvs = new Array();
  34481. var current_indice = 0;
  34482. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34483. var face_vertex_pos = new Array(3);
  34484. var face_vertex_uv = new Array(3);
  34485. var v012;
  34486. for (v012 = 0; v012 < 3; v012++) {
  34487. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34488. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34489. }
  34490. // create all with normals
  34491. for (var face = 0; face < 20; face++) {
  34492. // 3 vertex per face
  34493. for (v012 = 0; v012 < 3; v012++) {
  34494. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34495. var v_id = ico_indices[3 * face + v012];
  34496. // vertex have 3D position (x,y,z)
  34497. 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]);
  34498. // Normalize to get normal, then scale to radius
  34499. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34500. // uv Coordinates from vertex ID
  34501. 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);
  34502. }
  34503. // Subdivide the face (interpolate pos, norm, uv)
  34504. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34505. // - norm is linear interpolation of vertex corner normal
  34506. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34507. // - uv is linear interpolation
  34508. //
  34509. // Topology is as below for sub-divide by 2
  34510. // vertex shown as v0,v1,v2
  34511. // interp index is i1 to progress in range [v0,v1[
  34512. // interp index is i2 to progress in range [v0,v2[
  34513. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34514. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34515. //
  34516. //
  34517. // i2 v2
  34518. // ^ ^
  34519. // / / \
  34520. // / / \
  34521. // / / \
  34522. // / / (0,1) \
  34523. // / #---------\
  34524. // / / \ (0,0)'/ \
  34525. // / / \ / \
  34526. // / / \ / \
  34527. // / / (0,0) \ / (1,0) \
  34528. // / #---------#---------\
  34529. // v0 v1
  34530. //
  34531. // --------------------> i1
  34532. //
  34533. // interp of (i1,i2):
  34534. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34535. // along i1 : lerp(x0,x1, i1/(S-i2))
  34536. //
  34537. // centroid of triangle is needed to get help normal computation
  34538. // (c1,c2) are used for centroid location
  34539. var interp_vertex = function (i1, i2, c1, c2) {
  34540. // vertex is interpolated from
  34541. // - face_vertex_pos[0..2]
  34542. // - face_vertex_uv[0..2]
  34543. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34544. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34545. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34546. pos_interp.normalize();
  34547. var vertex_normal;
  34548. if (flat) {
  34549. // in flat mode, recalculate normal as face centroid normal
  34550. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34551. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34552. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34553. }
  34554. else {
  34555. // in smooth mode, recalculate normal from each single vertex position
  34556. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34557. }
  34558. // Vertex normal need correction due to X,Y,Z radius scaling
  34559. vertex_normal.x /= radiusX;
  34560. vertex_normal.y /= radiusY;
  34561. vertex_normal.z /= radiusZ;
  34562. vertex_normal.normalize();
  34563. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34564. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34565. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34566. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34567. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34568. uvs.push(uv_interp.x, uv_interp.y);
  34569. // push each vertex has member of a face
  34570. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34571. indices.push(current_indice);
  34572. current_indice++;
  34573. };
  34574. for (var i2 = 0; i2 < subdivisions; i2++) {
  34575. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34576. // face : (i1,i2) for /\ :
  34577. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34578. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34579. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34580. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34581. if (i1 + i2 + 1 < subdivisions) {
  34582. // face : (i1,i2)' for \/ :
  34583. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34584. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34585. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34586. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34587. }
  34588. }
  34589. }
  34590. }
  34591. // Sides
  34592. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34593. // Result
  34594. var vertexData = new VertexData();
  34595. vertexData.indices = indices;
  34596. vertexData.positions = positions;
  34597. vertexData.normals = normals;
  34598. vertexData.uvs = uvs;
  34599. return vertexData;
  34600. };
  34601. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34602. /**
  34603. * Creates the VertexData of the Polyhedron.
  34604. */
  34605. VertexData.CreatePolyhedron = function (options) {
  34606. // provided polyhedron types :
  34607. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34608. // 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)
  34609. var polyhedra = [];
  34610. 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]] };
  34611. 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]] };
  34612. polyhedra[2] = {
  34613. 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]],
  34614. 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]]
  34615. };
  34616. polyhedra[3] = {
  34617. 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]],
  34618. 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]]
  34619. };
  34620. polyhedra[4] = {
  34621. 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]],
  34622. 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]]
  34623. };
  34624. 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]] };
  34625. 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]] };
  34626. 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]] };
  34627. 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]] };
  34628. 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]] };
  34629. 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]] };
  34630. 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]] };
  34631. 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]] };
  34632. 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]] };
  34633. polyhedra[14] = {
  34634. 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]],
  34635. 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]]
  34636. };
  34637. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34638. var size = options.size;
  34639. var sizeX = options.sizeX || size || 1;
  34640. var sizeY = options.sizeY || size || 1;
  34641. var sizeZ = options.sizeZ || size || 1;
  34642. var data = options.custom || polyhedra[type];
  34643. var nbfaces = data.face.length;
  34644. var faceUV = options.faceUV || new Array(nbfaces);
  34645. var faceColors = options.faceColors;
  34646. var flat = (options.flat === undefined) ? true : options.flat;
  34647. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34648. var positions = new Array();
  34649. var indices = new Array();
  34650. var normals = new Array();
  34651. var uvs = new Array();
  34652. var colors = new Array();
  34653. var index = 0;
  34654. var faceIdx = 0; // face cursor in the array "indexes"
  34655. var indexes = new Array();
  34656. var i = 0;
  34657. var f = 0;
  34658. var u, v, ang, x, y, tmp;
  34659. // default face colors and UV if undefined
  34660. if (flat) {
  34661. for (f = 0; f < nbfaces; f++) {
  34662. if (faceColors && faceColors[f] === undefined) {
  34663. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34664. }
  34665. if (faceUV && faceUV[f] === undefined) {
  34666. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34667. }
  34668. }
  34669. }
  34670. if (!flat) {
  34671. for (i = 0; i < data.vertex.length; i++) {
  34672. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34673. uvs.push(0, 0);
  34674. }
  34675. for (f = 0; f < nbfaces; f++) {
  34676. for (i = 0; i < data.face[f].length - 2; i++) {
  34677. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34678. }
  34679. }
  34680. }
  34681. else {
  34682. for (f = 0; f < nbfaces; f++) {
  34683. var fl = data.face[f].length; // number of vertices of the current face
  34684. ang = 2 * Math.PI / fl;
  34685. x = 0.5 * Math.tan(ang / 2);
  34686. y = 0.5;
  34687. // positions, uvs, colors
  34688. for (i = 0; i < fl; i++) {
  34689. // positions
  34690. 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);
  34691. indexes.push(index);
  34692. index++;
  34693. // uvs
  34694. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34695. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34696. uvs.push(u, v);
  34697. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34698. y = x * Math.sin(ang) + y * Math.cos(ang);
  34699. x = tmp;
  34700. // colors
  34701. if (faceColors) {
  34702. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34703. }
  34704. }
  34705. // indices from indexes
  34706. for (i = 0; i < fl - 2; i++) {
  34707. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34708. }
  34709. faceIdx += fl;
  34710. }
  34711. }
  34712. VertexData.ComputeNormals(positions, indices, normals);
  34713. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34714. var vertexData = new VertexData();
  34715. vertexData.positions = positions;
  34716. vertexData.indices = indices;
  34717. vertexData.normals = normals;
  34718. vertexData.uvs = uvs;
  34719. if (faceColors && flat) {
  34720. vertexData.colors = colors;
  34721. }
  34722. return vertexData;
  34723. };
  34724. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34725. /**
  34726. * Creates the VertexData of the Torus Knot.
  34727. */
  34728. VertexData.CreateTorusKnot = function (options) {
  34729. var indices = new Array();
  34730. var positions = new Array();
  34731. var normals = new Array();
  34732. var uvs = new Array();
  34733. var radius = options.radius || 2;
  34734. var tube = options.tube || 0.5;
  34735. var radialSegments = options.radialSegments || 32;
  34736. var tubularSegments = options.tubularSegments || 32;
  34737. var p = options.p || 2;
  34738. var q = options.q || 3;
  34739. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34740. // Helper
  34741. var getPos = function (angle) {
  34742. var cu = Math.cos(angle);
  34743. var su = Math.sin(angle);
  34744. var quOverP = q / p * angle;
  34745. var cs = Math.cos(quOverP);
  34746. var tx = radius * (2 + cs) * 0.5 * cu;
  34747. var ty = radius * (2 + cs) * su * 0.5;
  34748. var tz = radius * Math.sin(quOverP) * 0.5;
  34749. return new BABYLON.Vector3(tx, ty, tz);
  34750. };
  34751. // Vertices
  34752. var i;
  34753. var j;
  34754. for (i = 0; i <= radialSegments; i++) {
  34755. var modI = i % radialSegments;
  34756. var u = modI / radialSegments * 2 * p * Math.PI;
  34757. var p1 = getPos(u);
  34758. var p2 = getPos(u + 0.01);
  34759. var tang = p2.subtract(p1);
  34760. var n = p2.add(p1);
  34761. var bitan = BABYLON.Vector3.Cross(tang, n);
  34762. n = BABYLON.Vector3.Cross(bitan, tang);
  34763. bitan.normalize();
  34764. n.normalize();
  34765. for (j = 0; j < tubularSegments; j++) {
  34766. var modJ = j % tubularSegments;
  34767. var v = modJ / tubularSegments * 2 * Math.PI;
  34768. var cx = -tube * Math.cos(v);
  34769. var cy = tube * Math.sin(v);
  34770. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34771. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34772. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34773. uvs.push(i / radialSegments);
  34774. uvs.push(j / tubularSegments);
  34775. }
  34776. }
  34777. for (i = 0; i < radialSegments; i++) {
  34778. for (j = 0; j < tubularSegments; j++) {
  34779. var jNext = (j + 1) % tubularSegments;
  34780. var a = i * tubularSegments + j;
  34781. var b = (i + 1) * tubularSegments + j;
  34782. var c = (i + 1) * tubularSegments + jNext;
  34783. var d = i * tubularSegments + jNext;
  34784. indices.push(d);
  34785. indices.push(b);
  34786. indices.push(a);
  34787. indices.push(d);
  34788. indices.push(c);
  34789. indices.push(b);
  34790. }
  34791. }
  34792. // Normals
  34793. VertexData.ComputeNormals(positions, indices, normals);
  34794. // Sides
  34795. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34796. // Result
  34797. var vertexData = new VertexData();
  34798. vertexData.indices = indices;
  34799. vertexData.positions = positions;
  34800. vertexData.normals = normals;
  34801. vertexData.uvs = uvs;
  34802. return vertexData;
  34803. };
  34804. // Tools
  34805. /**
  34806. * @param {any} - positions (number[] or Float32Array)
  34807. * @param {any} - indices (number[] or Uint16Array)
  34808. * @param {any} - normals (number[] or Float32Array)
  34809. * options (optional) :
  34810. * facetPositions : optional array of facet positions (vector3)
  34811. * facetNormals : optional array of facet normals (vector3)
  34812. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34813. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34814. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34815. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34816. * bInfo : optional bounding info, required for facetPartitioning computation
  34817. * useRightHandedSystem: optional boolean to for right handed system computation
  34818. * depthSort : optional boolean to enable the facet depth sort computation
  34819. * distanceTo : optional Vector3 to compute the facet depth from this location
  34820. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34821. */
  34822. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34823. // temporary scalar variables
  34824. var index = 0; // facet index
  34825. var p1p2x = 0.0; // p1p2 vector x coordinate
  34826. var p1p2y = 0.0; // p1p2 vector y coordinate
  34827. var p1p2z = 0.0; // p1p2 vector z coordinate
  34828. var p3p2x = 0.0; // p3p2 vector x coordinate
  34829. var p3p2y = 0.0; // p3p2 vector y coordinate
  34830. var p3p2z = 0.0; // p3p2 vector z coordinate
  34831. var faceNormalx = 0.0; // facet normal x coordinate
  34832. var faceNormaly = 0.0; // facet normal y coordinate
  34833. var faceNormalz = 0.0; // facet normal z coordinate
  34834. var length = 0.0; // facet normal length before normalization
  34835. var v1x = 0; // vector1 x index in the positions array
  34836. var v1y = 0; // vector1 y index in the positions array
  34837. var v1z = 0; // vector1 z index in the positions array
  34838. var v2x = 0; // vector2 x index in the positions array
  34839. var v2y = 0; // vector2 y index in the positions array
  34840. var v2z = 0; // vector2 z index in the positions array
  34841. var v3x = 0; // vector3 x index in the positions array
  34842. var v3y = 0; // vector3 y index in the positions array
  34843. var v3z = 0; // vector3 z index in the positions array
  34844. var computeFacetNormals = false;
  34845. var computeFacetPositions = false;
  34846. var computeFacetPartitioning = false;
  34847. var computeDepthSort = false;
  34848. var faceNormalSign = 1;
  34849. var ratio = 0;
  34850. var distanceTo = null;
  34851. if (options) {
  34852. computeFacetNormals = (options.facetNormals) ? true : false;
  34853. computeFacetPositions = (options.facetPositions) ? true : false;
  34854. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34855. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34856. ratio = options.ratio || 0;
  34857. computeDepthSort = (options.depthSort) ? true : false;
  34858. distanceTo = (options.distanceTo);
  34859. if (computeDepthSort) {
  34860. if (distanceTo === undefined) {
  34861. distanceTo = BABYLON.Vector3.Zero();
  34862. }
  34863. var depthSortedFacets = options.depthSortedFacets;
  34864. }
  34865. }
  34866. // facetPartitioning reinit if needed
  34867. var xSubRatio = 0;
  34868. var ySubRatio = 0;
  34869. var zSubRatio = 0;
  34870. var subSq = 0;
  34871. if (computeFacetPartitioning && options && options.bbSize) {
  34872. var ox = 0; // X partitioning index for facet position
  34873. var oy = 0; // Y partinioning index for facet position
  34874. var oz = 0; // Z partinioning index for facet position
  34875. var b1x = 0; // X partitioning index for facet v1 vertex
  34876. var b1y = 0; // Y partitioning index for facet v1 vertex
  34877. var b1z = 0; // z partitioning index for facet v1 vertex
  34878. var b2x = 0; // X partitioning index for facet v2 vertex
  34879. var b2y = 0; // Y partitioning index for facet v2 vertex
  34880. var b2z = 0; // Z partitioning index for facet v2 vertex
  34881. var b3x = 0; // X partitioning index for facet v3 vertex
  34882. var b3y = 0; // Y partitioning index for facet v3 vertex
  34883. var b3z = 0; // Z partitioning index for facet v3 vertex
  34884. var block_idx_o = 0; // facet barycenter block index
  34885. var block_idx_v1 = 0; // v1 vertex block index
  34886. var block_idx_v2 = 0; // v2 vertex block index
  34887. var block_idx_v3 = 0; // v3 vertex block index
  34888. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34889. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34890. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34891. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34892. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34893. subSq = options.subDiv.max * options.subDiv.max;
  34894. options.facetPartitioning.length = 0;
  34895. }
  34896. // reset the normals
  34897. for (index = 0; index < positions.length; index++) {
  34898. normals[index] = 0.0;
  34899. }
  34900. // Loop : 1 indice triplet = 1 facet
  34901. var nbFaces = (indices.length / 3) | 0;
  34902. for (index = 0; index < nbFaces; index++) {
  34903. // get the indexes of the coordinates of each vertex of the facet
  34904. v1x = indices[index * 3] * 3;
  34905. v1y = v1x + 1;
  34906. v1z = v1x + 2;
  34907. v2x = indices[index * 3 + 1] * 3;
  34908. v2y = v2x + 1;
  34909. v2z = v2x + 2;
  34910. v3x = indices[index * 3 + 2] * 3;
  34911. v3y = v3x + 1;
  34912. v3z = v3x + 2;
  34913. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34914. p1p2y = positions[v1y] - positions[v2y];
  34915. p1p2z = positions[v1z] - positions[v2z];
  34916. p3p2x = positions[v3x] - positions[v2x];
  34917. p3p2y = positions[v3y] - positions[v2y];
  34918. p3p2z = positions[v3z] - positions[v2z];
  34919. // compute the face normal with the cross product
  34920. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34921. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34922. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34923. // normalize this normal and store it in the array facetData
  34924. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34925. length = (length === 0) ? 1.0 : length;
  34926. faceNormalx /= length;
  34927. faceNormaly /= length;
  34928. faceNormalz /= length;
  34929. if (computeFacetNormals && options) {
  34930. options.facetNormals[index].x = faceNormalx;
  34931. options.facetNormals[index].y = faceNormaly;
  34932. options.facetNormals[index].z = faceNormalz;
  34933. }
  34934. if (computeFacetPositions && options) {
  34935. // compute and the facet barycenter coordinates in the array facetPositions
  34936. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34937. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34938. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34939. }
  34940. if (computeFacetPartitioning && options) {
  34941. // store the facet indexes in arrays in the main facetPartitioning array :
  34942. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34943. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34944. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34945. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34946. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34947. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34948. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34949. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34950. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34951. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34952. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34953. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34954. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34955. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34956. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34957. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34958. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34959. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34960. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34961. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34962. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34963. // push each facet index in each block containing the vertex
  34964. options.facetPartitioning[block_idx_v1].push(index);
  34965. if (block_idx_v2 != block_idx_v1) {
  34966. options.facetPartitioning[block_idx_v2].push(index);
  34967. }
  34968. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34969. options.facetPartitioning[block_idx_v3].push(index);
  34970. }
  34971. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34972. options.facetPartitioning[block_idx_o].push(index);
  34973. }
  34974. }
  34975. if (computeDepthSort && options && options.facetPositions) {
  34976. var dsf = depthSortedFacets[index];
  34977. dsf.ind = index * 3;
  34978. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34979. }
  34980. // compute the normals anyway
  34981. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34982. normals[v1y] += faceNormaly;
  34983. normals[v1z] += faceNormalz;
  34984. normals[v2x] += faceNormalx;
  34985. normals[v2y] += faceNormaly;
  34986. normals[v2z] += faceNormalz;
  34987. normals[v3x] += faceNormalx;
  34988. normals[v3y] += faceNormaly;
  34989. normals[v3z] += faceNormalz;
  34990. }
  34991. // last normalization of each normal
  34992. for (index = 0; index < normals.length / 3; index++) {
  34993. faceNormalx = normals[index * 3];
  34994. faceNormaly = normals[index * 3 + 1];
  34995. faceNormalz = normals[index * 3 + 2];
  34996. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34997. length = (length === 0) ? 1.0 : length;
  34998. faceNormalx /= length;
  34999. faceNormaly /= length;
  35000. faceNormalz /= length;
  35001. normals[index * 3] = faceNormalx;
  35002. normals[index * 3 + 1] = faceNormaly;
  35003. normals[index * 3 + 2] = faceNormalz;
  35004. }
  35005. };
  35006. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  35007. var li = indices.length;
  35008. var ln = normals.length;
  35009. var i;
  35010. var n;
  35011. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35012. switch (sideOrientation) {
  35013. case BABYLON.Mesh.FRONTSIDE:
  35014. // nothing changed
  35015. break;
  35016. case BABYLON.Mesh.BACKSIDE:
  35017. var tmp;
  35018. // indices
  35019. for (i = 0; i < li; i += 3) {
  35020. tmp = indices[i];
  35021. indices[i] = indices[i + 2];
  35022. indices[i + 2] = tmp;
  35023. }
  35024. // normals
  35025. for (n = 0; n < ln; n++) {
  35026. normals[n] = -normals[n];
  35027. }
  35028. break;
  35029. case BABYLON.Mesh.DOUBLESIDE:
  35030. // positions
  35031. var lp = positions.length;
  35032. var l = lp / 3;
  35033. for (var p = 0; p < lp; p++) {
  35034. positions[lp + p] = positions[p];
  35035. }
  35036. // indices
  35037. for (i = 0; i < li; i += 3) {
  35038. indices[i + li] = indices[i + 2] + l;
  35039. indices[i + 1 + li] = indices[i + 1] + l;
  35040. indices[i + 2 + li] = indices[i] + l;
  35041. }
  35042. // normals
  35043. for (n = 0; n < ln; n++) {
  35044. normals[ln + n] = -normals[n];
  35045. }
  35046. // uvs
  35047. var lu = uvs.length;
  35048. var u = 0;
  35049. for (u = 0; u < lu; u++) {
  35050. uvs[u + lu] = uvs[u];
  35051. }
  35052. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35053. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35054. u = 0;
  35055. for (i = 0; i < lu / 2; i++) {
  35056. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  35057. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  35058. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  35059. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  35060. u += 2;
  35061. }
  35062. break;
  35063. }
  35064. };
  35065. /**
  35066. * Creates a new VertexData from the imported parameters.
  35067. */
  35068. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  35069. var vertexData = new VertexData();
  35070. // positions
  35071. var positions = parsedVertexData.positions;
  35072. if (positions) {
  35073. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35074. }
  35075. // normals
  35076. var normals = parsedVertexData.normals;
  35077. if (normals) {
  35078. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35079. }
  35080. // tangents
  35081. var tangents = parsedVertexData.tangents;
  35082. if (tangents) {
  35083. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  35084. }
  35085. // uvs
  35086. var uvs = parsedVertexData.uvs;
  35087. if (uvs) {
  35088. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35089. }
  35090. // uv2s
  35091. var uv2s = parsedVertexData.uv2s;
  35092. if (uv2s) {
  35093. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35094. }
  35095. // uv3s
  35096. var uv3s = parsedVertexData.uv3s;
  35097. if (uv3s) {
  35098. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35099. }
  35100. // uv4s
  35101. var uv4s = parsedVertexData.uv4s;
  35102. if (uv4s) {
  35103. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35104. }
  35105. // uv5s
  35106. var uv5s = parsedVertexData.uv5s;
  35107. if (uv5s) {
  35108. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35109. }
  35110. // uv6s
  35111. var uv6s = parsedVertexData.uv6s;
  35112. if (uv6s) {
  35113. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35114. }
  35115. // colors
  35116. var colors = parsedVertexData.colors;
  35117. if (colors) {
  35118. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35119. }
  35120. // matricesIndices
  35121. var matricesIndices = parsedVertexData.matricesIndices;
  35122. if (matricesIndices) {
  35123. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35124. }
  35125. // matricesWeights
  35126. var matricesWeights = parsedVertexData.matricesWeights;
  35127. if (matricesWeights) {
  35128. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35129. }
  35130. // indices
  35131. var indices = parsedVertexData.indices;
  35132. if (indices) {
  35133. vertexData.indices = indices;
  35134. }
  35135. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35136. };
  35137. return VertexData;
  35138. }());
  35139. BABYLON.VertexData = VertexData;
  35140. })(BABYLON || (BABYLON = {}));
  35141. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35142. "use strict";
  35143. var BABYLON;
  35144. (function (BABYLON) {
  35145. /**
  35146. * Class used to store geometry data (vertex buffers + index buffer)
  35147. */
  35148. var Geometry = /** @class */ (function () {
  35149. /**
  35150. * Creates a new geometry
  35151. * @param id defines the unique ID
  35152. * @param scene defines the hosting scene
  35153. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  35154. * @param updatable defines if geometry must be updatable (false by default)
  35155. * @param mesh defines the mesh that will be associated with the geometry
  35156. */
  35157. function Geometry(id, scene, vertexData, updatable, mesh) {
  35158. if (updatable === void 0) { updatable = false; }
  35159. if (mesh === void 0) { mesh = null; }
  35160. /**
  35161. * Gets the delay loading state of the geometry (none by default which means not delayed)
  35162. */
  35163. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35164. this._totalVertices = 0;
  35165. this._isDisposed = false;
  35166. this._indexBufferIsUpdatable = false;
  35167. this.id = id;
  35168. this._engine = scene.getEngine();
  35169. this._meshes = [];
  35170. this._scene = scene;
  35171. //Init vertex buffer cache
  35172. this._vertexBuffers = {};
  35173. this._indices = [];
  35174. this._updatable = updatable;
  35175. // vertexData
  35176. if (vertexData) {
  35177. this.setAllVerticesData(vertexData, updatable);
  35178. }
  35179. else {
  35180. this._totalVertices = 0;
  35181. this._indices = [];
  35182. }
  35183. if (this._engine.getCaps().vertexArrayObject) {
  35184. this._vertexArrayObjects = {};
  35185. }
  35186. // applyToMesh
  35187. if (mesh) {
  35188. if (mesh.getClassName() === "LinesMesh") {
  35189. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  35190. this.updateExtend();
  35191. }
  35192. this.applyToMesh(mesh);
  35193. mesh.computeWorldMatrix(true);
  35194. }
  35195. }
  35196. Object.defineProperty(Geometry.prototype, "boundingBias", {
  35197. /**
  35198. * 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
  35199. */
  35200. get: function () {
  35201. return this._boundingBias;
  35202. },
  35203. /**
  35204. * 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
  35205. */
  35206. set: function (value) {
  35207. if (this._boundingBias && this._boundingBias.equals(value)) {
  35208. return;
  35209. }
  35210. this._boundingBias = value.clone();
  35211. this.updateBoundingInfo(true, null);
  35212. },
  35213. enumerable: true,
  35214. configurable: true
  35215. });
  35216. /**
  35217. * Static function used to attach a new empty geometry to a mesh
  35218. * @param mesh defines the mesh to attach the geometry to
  35219. * @returns the new {BABYLON.Geometry}
  35220. */
  35221. Geometry.CreateGeometryForMesh = function (mesh) {
  35222. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  35223. geometry.applyToMesh(mesh);
  35224. return geometry;
  35225. };
  35226. Object.defineProperty(Geometry.prototype, "extend", {
  35227. /**
  35228. * Gets the current extend of the geometry
  35229. */
  35230. get: function () {
  35231. return this._extend;
  35232. },
  35233. enumerable: true,
  35234. configurable: true
  35235. });
  35236. /**
  35237. * Gets the hosting scene
  35238. * @returns the hosting {BABYLON.Scene}
  35239. */
  35240. Geometry.prototype.getScene = function () {
  35241. return this._scene;
  35242. };
  35243. /**
  35244. * Gets the hosting engine
  35245. * @returns the hosting {BABYLON.Engine}
  35246. */
  35247. Geometry.prototype.getEngine = function () {
  35248. return this._engine;
  35249. };
  35250. /**
  35251. * Defines if the geometry is ready to use
  35252. * @returns true if the geometry is ready to be used
  35253. */
  35254. Geometry.prototype.isReady = function () {
  35255. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  35256. };
  35257. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  35258. /**
  35259. * Gets a value indicating that the geometry should not be serialized
  35260. */
  35261. get: function () {
  35262. for (var index = 0; index < this._meshes.length; index++) {
  35263. if (!this._meshes[index].doNotSerialize) {
  35264. return false;
  35265. }
  35266. }
  35267. return true;
  35268. },
  35269. enumerable: true,
  35270. configurable: true
  35271. });
  35272. /** @ignore */
  35273. Geometry.prototype._rebuild = function () {
  35274. if (this._vertexArrayObjects) {
  35275. this._vertexArrayObjects = {};
  35276. }
  35277. // Index buffer
  35278. if (this._meshes.length !== 0 && this._indices) {
  35279. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35280. }
  35281. // Vertex buffers
  35282. for (var key in this._vertexBuffers) {
  35283. var vertexBuffer = this._vertexBuffers[key];
  35284. vertexBuffer._rebuild();
  35285. }
  35286. };
  35287. /**
  35288. * Affects all gemetry data in one call
  35289. * @param vertexData defines the geometry data
  35290. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  35291. */
  35292. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35293. vertexData.applyToGeometry(this, updatable);
  35294. this.notifyUpdate();
  35295. };
  35296. /**
  35297. * Set specific vertex data
  35298. * @param kind defines the data kind (Position, normal, etc...)
  35299. * @param data defines the vertex data to use
  35300. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  35301. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  35302. */
  35303. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  35304. if (updatable === void 0) { updatable = false; }
  35305. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  35306. this.setVerticesBuffer(buffer);
  35307. };
  35308. /**
  35309. * Removes a specific vertex data
  35310. * @param kind defines the data kind (Position, normal, etc...)
  35311. */
  35312. Geometry.prototype.removeVerticesData = function (kind) {
  35313. if (this._vertexBuffers[kind]) {
  35314. this._vertexBuffers[kind].dispose();
  35315. delete this._vertexBuffers[kind];
  35316. }
  35317. };
  35318. /**
  35319. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  35320. * @param buffer defines the vertex buffer to use
  35321. */
  35322. Geometry.prototype.setVerticesBuffer = function (buffer) {
  35323. var kind = buffer.getKind();
  35324. if (this._vertexBuffers[kind]) {
  35325. this._vertexBuffers[kind].dispose();
  35326. }
  35327. this._vertexBuffers[kind] = buffer;
  35328. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35329. var data = buffer.getData();
  35330. var stride = buffer.getStrideSize();
  35331. this._totalVertices = data.length / stride;
  35332. this.updateExtend(data, stride);
  35333. this._resetPointsArrayCache();
  35334. var meshes = this._meshes;
  35335. var numOfMeshes = meshes.length;
  35336. for (var index = 0; index < numOfMeshes; index++) {
  35337. var mesh = meshes[index];
  35338. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35339. mesh._createGlobalSubMesh(false);
  35340. mesh.computeWorldMatrix(true);
  35341. }
  35342. }
  35343. this.notifyUpdate(kind);
  35344. if (this._vertexArrayObjects) {
  35345. this._disposeVertexArrayObjects();
  35346. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  35347. }
  35348. };
  35349. /**
  35350. * Update a specific vertex buffer
  35351. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  35352. * It will do nothing if the buffer is not updatable
  35353. * @param kind defines the data kind (Position, normal, etc...)
  35354. * @param data defines the data to use
  35355. * @param offset defines the offset in the target buffer where to store the data
  35356. */
  35357. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35358. var vertexBuffer = this.getVertexBuffer(kind);
  35359. if (!vertexBuffer) {
  35360. return;
  35361. }
  35362. vertexBuffer.updateDirectly(data, offset);
  35363. this.notifyUpdate(kind);
  35364. };
  35365. /**
  35366. * Update a specific vertex buffer
  35367. * This function will create a new buffer if the current one is not updatable
  35368. * @param kind defines the data kind (Position, normal, etc...)
  35369. * @param data defines the data to use
  35370. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  35371. */
  35372. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35373. if (updateExtends === void 0) { updateExtends = false; }
  35374. var vertexBuffer = this.getVertexBuffer(kind);
  35375. if (!vertexBuffer) {
  35376. return;
  35377. }
  35378. vertexBuffer.update(data);
  35379. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35380. var stride = vertexBuffer.getStrideSize();
  35381. this._totalVertices = data.length / stride;
  35382. this.updateBoundingInfo(updateExtends, data);
  35383. }
  35384. this.notifyUpdate(kind);
  35385. };
  35386. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35387. if (updateExtends) {
  35388. this.updateExtend(data);
  35389. }
  35390. var meshes = this._meshes;
  35391. var numOfMeshes = meshes.length;
  35392. this._resetPointsArrayCache();
  35393. for (var index = 0; index < numOfMeshes; index++) {
  35394. var mesh = meshes[index];
  35395. if (updateExtends) {
  35396. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35397. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35398. var subMesh = mesh.subMeshes[subIndex];
  35399. subMesh.refreshBoundingInfo();
  35400. }
  35401. }
  35402. }
  35403. };
  35404. /** @ignore */
  35405. Geometry.prototype._bind = function (effect, indexToBind) {
  35406. if (!effect) {
  35407. return;
  35408. }
  35409. if (indexToBind === undefined) {
  35410. indexToBind = this._indexBuffer;
  35411. }
  35412. var vbs = this.getVertexBuffers();
  35413. if (!vbs) {
  35414. return;
  35415. }
  35416. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35417. this._engine.bindBuffers(vbs, indexToBind, effect);
  35418. return;
  35419. }
  35420. // Using VAO
  35421. if (!this._vertexArrayObjects[effect.key]) {
  35422. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35423. }
  35424. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35425. };
  35426. /**
  35427. * Gets total number of vertices
  35428. * @returns the total number of vertices
  35429. */
  35430. Geometry.prototype.getTotalVertices = function () {
  35431. if (!this.isReady()) {
  35432. return 0;
  35433. }
  35434. return this._totalVertices;
  35435. };
  35436. /**
  35437. * Gets a specific vertex data attached to this geometry
  35438. * @param kind defines the data kind (Position, normal, etc...)
  35439. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35440. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35441. * @returns a float array containing vertex data
  35442. */
  35443. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35444. var vertexBuffer = this.getVertexBuffer(kind);
  35445. if (!vertexBuffer) {
  35446. return null;
  35447. }
  35448. var orig = vertexBuffer.getData();
  35449. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35450. return orig;
  35451. }
  35452. else {
  35453. var len = orig.length;
  35454. var copy = [];
  35455. for (var i = 0; i < len; i++) {
  35456. copy.push(orig[i]);
  35457. }
  35458. return copy;
  35459. }
  35460. };
  35461. /**
  35462. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35463. * @param kind defines the data kind (Position, normal, etc...)
  35464. * @returns true if the vertex buffer with the specified kind is updatable
  35465. */
  35466. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35467. var vb = this._vertexBuffers[kind];
  35468. if (!vb) {
  35469. return false;
  35470. }
  35471. return vb.isUpdatable();
  35472. };
  35473. /**
  35474. * Gets a specific vertex buffer
  35475. * @param kind defines the data kind (Position, normal, etc...)
  35476. * @returns a {BABYLON.VertexBuffer}
  35477. */
  35478. Geometry.prototype.getVertexBuffer = function (kind) {
  35479. if (!this.isReady()) {
  35480. return null;
  35481. }
  35482. return this._vertexBuffers[kind];
  35483. };
  35484. /**
  35485. * Returns all vertex buffers
  35486. * @return an object holding all vertex buffers indexed by kind
  35487. */
  35488. Geometry.prototype.getVertexBuffers = function () {
  35489. if (!this.isReady()) {
  35490. return null;
  35491. }
  35492. return this._vertexBuffers;
  35493. };
  35494. /**
  35495. * Gets a boolean indicating if specific vertex buffer is present
  35496. * @param kind defines the data kind (Position, normal, etc...)
  35497. * @returns true if data is present
  35498. */
  35499. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35500. if (!this._vertexBuffers) {
  35501. if (this._delayInfo) {
  35502. return this._delayInfo.indexOf(kind) !== -1;
  35503. }
  35504. return false;
  35505. }
  35506. return this._vertexBuffers[kind] !== undefined;
  35507. };
  35508. /**
  35509. * Gets a list of all attached data kinds (Position, normal, etc...)
  35510. * @returns a list of string containing all kinds
  35511. */
  35512. Geometry.prototype.getVerticesDataKinds = function () {
  35513. var result = [];
  35514. var kind;
  35515. if (!this._vertexBuffers && this._delayInfo) {
  35516. for (kind in this._delayInfo) {
  35517. result.push(kind);
  35518. }
  35519. }
  35520. else {
  35521. for (kind in this._vertexBuffers) {
  35522. result.push(kind);
  35523. }
  35524. }
  35525. return result;
  35526. };
  35527. /**
  35528. * Update index buffer
  35529. * @param indices defines the indices to store in the index buffer
  35530. * @param offset defines the offset in the target buffer where to store the data
  35531. */
  35532. Geometry.prototype.updateIndices = function (indices, offset) {
  35533. if (!this._indexBuffer) {
  35534. return;
  35535. }
  35536. if (!this._indexBufferIsUpdatable) {
  35537. this.setIndices(indices, null, true);
  35538. }
  35539. else {
  35540. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35541. }
  35542. };
  35543. /**
  35544. * Creates a new index buffer
  35545. * @param indices defines the indices to store in the index buffer
  35546. * @param totalVertices defines the total number of vertices (could be null)
  35547. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35548. */
  35549. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35550. if (totalVertices === void 0) { totalVertices = null; }
  35551. if (updatable === void 0) { updatable = false; }
  35552. if (this._indexBuffer) {
  35553. this._engine._releaseBuffer(this._indexBuffer);
  35554. }
  35555. this._disposeVertexArrayObjects();
  35556. this._indices = indices;
  35557. this._indexBufferIsUpdatable = updatable;
  35558. if (this._meshes.length !== 0 && this._indices) {
  35559. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35560. }
  35561. if (totalVertices != undefined) {
  35562. this._totalVertices = totalVertices;
  35563. }
  35564. var meshes = this._meshes;
  35565. var numOfMeshes = meshes.length;
  35566. for (var index = 0; index < numOfMeshes; index++) {
  35567. meshes[index]._createGlobalSubMesh(true);
  35568. }
  35569. this.notifyUpdate();
  35570. };
  35571. /**
  35572. * Return the total number of indices
  35573. * @returns the total number of indices
  35574. */
  35575. Geometry.prototype.getTotalIndices = function () {
  35576. if (!this.isReady()) {
  35577. return 0;
  35578. }
  35579. return this._indices.length;
  35580. };
  35581. /**
  35582. * Gets the index buffer array
  35583. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35584. * @returns the index buffer array
  35585. */
  35586. Geometry.prototype.getIndices = function (copyWhenShared) {
  35587. if (!this.isReady()) {
  35588. return null;
  35589. }
  35590. var orig = this._indices;
  35591. if (!copyWhenShared || this._meshes.length === 1) {
  35592. return orig;
  35593. }
  35594. else {
  35595. var len = orig.length;
  35596. var copy = [];
  35597. for (var i = 0; i < len; i++) {
  35598. copy.push(orig[i]);
  35599. }
  35600. return copy;
  35601. }
  35602. };
  35603. /**
  35604. * Gets the index buffer
  35605. * @return the index buffer
  35606. */
  35607. Geometry.prototype.getIndexBuffer = function () {
  35608. if (!this.isReady()) {
  35609. return null;
  35610. }
  35611. return this._indexBuffer;
  35612. };
  35613. /** @ignore */
  35614. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35615. if (effect === void 0) { effect = null; }
  35616. if (!effect || !this._vertexArrayObjects) {
  35617. return;
  35618. }
  35619. if (this._vertexArrayObjects[effect.key]) {
  35620. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35621. delete this._vertexArrayObjects[effect.key];
  35622. }
  35623. };
  35624. /**
  35625. * Release the associated resources for a specific mesh
  35626. * @param mesh defines the source mesh
  35627. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35628. */
  35629. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35630. var meshes = this._meshes;
  35631. var index = meshes.indexOf(mesh);
  35632. if (index === -1) {
  35633. return;
  35634. }
  35635. meshes.splice(index, 1);
  35636. mesh._geometry = null;
  35637. if (meshes.length === 0 && shouldDispose) {
  35638. this.dispose();
  35639. }
  35640. };
  35641. /**
  35642. * Apply current geometry to a given mesh
  35643. * @param mesh defines the mesh to apply geometry to
  35644. */
  35645. Geometry.prototype.applyToMesh = function (mesh) {
  35646. if (mesh._geometry === this) {
  35647. return;
  35648. }
  35649. var previousGeometry = mesh._geometry;
  35650. if (previousGeometry) {
  35651. previousGeometry.releaseForMesh(mesh);
  35652. }
  35653. var meshes = this._meshes;
  35654. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35655. mesh._geometry = this;
  35656. this._scene.pushGeometry(this);
  35657. meshes.push(mesh);
  35658. if (this.isReady()) {
  35659. this._applyToMesh(mesh);
  35660. }
  35661. else {
  35662. mesh._boundingInfo = this._boundingInfo;
  35663. }
  35664. };
  35665. Geometry.prototype.updateExtend = function (data, stride) {
  35666. if (data === void 0) { data = null; }
  35667. if (!data) {
  35668. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35669. }
  35670. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35671. };
  35672. Geometry.prototype._applyToMesh = function (mesh) {
  35673. var numOfMeshes = this._meshes.length;
  35674. // vertexBuffers
  35675. for (var kind in this._vertexBuffers) {
  35676. if (numOfMeshes === 1) {
  35677. this._vertexBuffers[kind].create();
  35678. }
  35679. var buffer = this._vertexBuffers[kind].getBuffer();
  35680. if (buffer)
  35681. buffer.references = numOfMeshes;
  35682. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35683. if (!this._extend) {
  35684. this.updateExtend(this._vertexBuffers[kind].getData());
  35685. }
  35686. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35687. mesh._createGlobalSubMesh(false);
  35688. //bounding info was just created again, world matrix should be applied again.
  35689. mesh._updateBoundingInfo();
  35690. }
  35691. }
  35692. // indexBuffer
  35693. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35694. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35695. }
  35696. if (this._indexBuffer) {
  35697. this._indexBuffer.references = numOfMeshes;
  35698. }
  35699. };
  35700. Geometry.prototype.notifyUpdate = function (kind) {
  35701. if (this.onGeometryUpdated) {
  35702. this.onGeometryUpdated(this, kind);
  35703. }
  35704. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35705. var mesh = _a[_i];
  35706. mesh._markSubMeshesAsAttributesDirty();
  35707. }
  35708. };
  35709. /**
  35710. * Load the geometry if it was flagged as delay loaded
  35711. * @param scene defines the hosting scene
  35712. * @param onLoaded defines a callback called when the geometry is loaded
  35713. */
  35714. Geometry.prototype.load = function (scene, onLoaded) {
  35715. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35716. return;
  35717. }
  35718. if (this.isReady()) {
  35719. if (onLoaded) {
  35720. onLoaded();
  35721. }
  35722. return;
  35723. }
  35724. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35725. this._queueLoad(scene, onLoaded);
  35726. };
  35727. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35728. var _this = this;
  35729. if (!this.delayLoadingFile) {
  35730. return;
  35731. }
  35732. scene._addPendingData(this);
  35733. scene._loadFile(this.delayLoadingFile, function (data) {
  35734. if (!_this._delayLoadingFunction) {
  35735. return;
  35736. }
  35737. _this._delayLoadingFunction(JSON.parse(data), _this);
  35738. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35739. _this._delayInfo = [];
  35740. scene._removePendingData(_this);
  35741. var meshes = _this._meshes;
  35742. var numOfMeshes = meshes.length;
  35743. for (var index = 0; index < numOfMeshes; index++) {
  35744. _this._applyToMesh(meshes[index]);
  35745. }
  35746. if (onLoaded) {
  35747. onLoaded();
  35748. }
  35749. }, undefined, true);
  35750. };
  35751. /**
  35752. * Invert the geometry to move from a right handed system to a left handed one.
  35753. */
  35754. Geometry.prototype.toLeftHanded = function () {
  35755. // Flip faces
  35756. var tIndices = this.getIndices(false);
  35757. if (tIndices != null && tIndices.length > 0) {
  35758. for (var i = 0; i < tIndices.length; i += 3) {
  35759. var tTemp = tIndices[i + 0];
  35760. tIndices[i + 0] = tIndices[i + 2];
  35761. tIndices[i + 2] = tTemp;
  35762. }
  35763. this.setIndices(tIndices);
  35764. }
  35765. // Negate position.z
  35766. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35767. if (tPositions != null && tPositions.length > 0) {
  35768. for (var i = 0; i < tPositions.length; i += 3) {
  35769. tPositions[i + 2] = -tPositions[i + 2];
  35770. }
  35771. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35772. }
  35773. // Negate normal.z
  35774. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35775. if (tNormals != null && tNormals.length > 0) {
  35776. for (var i = 0; i < tNormals.length; i += 3) {
  35777. tNormals[i + 2] = -tNormals[i + 2];
  35778. }
  35779. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35780. }
  35781. };
  35782. // Cache
  35783. /** @ignore */
  35784. Geometry.prototype._resetPointsArrayCache = function () {
  35785. this._positions = null;
  35786. };
  35787. /** @ignore */
  35788. Geometry.prototype._generatePointsArray = function () {
  35789. if (this._positions)
  35790. return true;
  35791. this._positions = [];
  35792. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35793. if (!data) {
  35794. return false;
  35795. }
  35796. for (var index = 0; index < data.length; index += 3) {
  35797. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35798. }
  35799. return true;
  35800. };
  35801. /**
  35802. * Gets a value indicating if the geometry is disposed
  35803. * @returns true if the geometry was disposed
  35804. */
  35805. Geometry.prototype.isDisposed = function () {
  35806. return this._isDisposed;
  35807. };
  35808. Geometry.prototype._disposeVertexArrayObjects = function () {
  35809. if (this._vertexArrayObjects) {
  35810. for (var kind in this._vertexArrayObjects) {
  35811. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35812. }
  35813. this._vertexArrayObjects = {};
  35814. }
  35815. };
  35816. /**
  35817. * Free all associated resources
  35818. */
  35819. Geometry.prototype.dispose = function () {
  35820. var meshes = this._meshes;
  35821. var numOfMeshes = meshes.length;
  35822. var index;
  35823. for (index = 0; index < numOfMeshes; index++) {
  35824. this.releaseForMesh(meshes[index]);
  35825. }
  35826. this._meshes = [];
  35827. this._disposeVertexArrayObjects();
  35828. for (var kind in this._vertexBuffers) {
  35829. this._vertexBuffers[kind].dispose();
  35830. }
  35831. this._vertexBuffers = {};
  35832. this._totalVertices = 0;
  35833. if (this._indexBuffer) {
  35834. this._engine._releaseBuffer(this._indexBuffer);
  35835. }
  35836. this._indexBuffer = null;
  35837. this._indices = [];
  35838. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35839. this.delayLoadingFile = null;
  35840. this._delayLoadingFunction = null;
  35841. this._delayInfo = [];
  35842. this._boundingInfo = null;
  35843. this._scene.removeGeometry(this);
  35844. this._isDisposed = true;
  35845. };
  35846. /**
  35847. * Clone the current geometry into a new geometry
  35848. * @param id defines the unique ID of the new geometry
  35849. * @returns a new geometry object
  35850. */
  35851. Geometry.prototype.copy = function (id) {
  35852. var vertexData = new BABYLON.VertexData();
  35853. vertexData.indices = [];
  35854. var indices = this.getIndices();
  35855. if (indices) {
  35856. for (var index = 0; index < indices.length; index++) {
  35857. vertexData.indices.push(indices[index]);
  35858. }
  35859. }
  35860. var updatable = false;
  35861. var stopChecking = false;
  35862. var kind;
  35863. for (kind in this._vertexBuffers) {
  35864. // using slice() to make a copy of the array and not just reference it
  35865. var data = this.getVerticesData(kind);
  35866. if (data instanceof Float32Array) {
  35867. vertexData.set(new Float32Array(data), kind);
  35868. }
  35869. else {
  35870. vertexData.set(data.slice(0), kind);
  35871. }
  35872. if (!stopChecking) {
  35873. var vb = this.getVertexBuffer(kind);
  35874. if (vb) {
  35875. updatable = vb.isUpdatable();
  35876. stopChecking = !updatable;
  35877. }
  35878. }
  35879. }
  35880. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35881. geometry.delayLoadState = this.delayLoadState;
  35882. geometry.delayLoadingFile = this.delayLoadingFile;
  35883. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35884. for (kind in this._delayInfo) {
  35885. geometry._delayInfo = geometry._delayInfo || [];
  35886. geometry._delayInfo.push(kind);
  35887. }
  35888. // Bounding info
  35889. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35890. return geometry;
  35891. };
  35892. /**
  35893. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35894. * @return a JSON representation of the current geometry data (without the vertices data)
  35895. */
  35896. Geometry.prototype.serialize = function () {
  35897. var serializationObject = {};
  35898. serializationObject.id = this.id;
  35899. serializationObject.updatable = this._updatable;
  35900. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35901. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35902. }
  35903. return serializationObject;
  35904. };
  35905. Geometry.prototype.toNumberArray = function (origin) {
  35906. if (Array.isArray(origin)) {
  35907. return origin;
  35908. }
  35909. else {
  35910. return Array.prototype.slice.call(origin);
  35911. }
  35912. };
  35913. /**
  35914. * Serialize all vertices data into a JSON oject
  35915. * @returns a JSON representation of the current geometry data
  35916. */
  35917. Geometry.prototype.serializeVerticeData = function () {
  35918. var serializationObject = this.serialize();
  35919. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35920. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35921. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35922. serializationObject.positions._updatable = true;
  35923. }
  35924. }
  35925. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35926. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35927. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35928. serializationObject.normals._updatable = true;
  35929. }
  35930. }
  35931. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35932. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35933. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35934. serializationObject.tangets._updatable = true;
  35935. }
  35936. }
  35937. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35938. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35939. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35940. serializationObject.uvs._updatable = true;
  35941. }
  35942. }
  35943. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35944. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35945. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35946. serializationObject.uv2s._updatable = true;
  35947. }
  35948. }
  35949. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35950. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35951. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35952. serializationObject.uv3s._updatable = true;
  35953. }
  35954. }
  35955. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35956. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35957. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35958. serializationObject.uv4s._updatable = true;
  35959. }
  35960. }
  35961. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35962. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35963. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35964. serializationObject.uv5s._updatable = true;
  35965. }
  35966. }
  35967. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35968. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35969. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35970. serializationObject.uv6s._updatable = true;
  35971. }
  35972. }
  35973. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35974. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35975. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35976. serializationObject.colors._updatable = true;
  35977. }
  35978. }
  35979. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35980. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35981. serializationObject.matricesIndices._isExpanded = true;
  35982. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35983. serializationObject.matricesIndices._updatable = true;
  35984. }
  35985. }
  35986. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35987. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35988. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35989. serializationObject.matricesWeights._updatable = true;
  35990. }
  35991. }
  35992. serializationObject.indices = this.toNumberArray(this.getIndices());
  35993. return serializationObject;
  35994. };
  35995. // Statics
  35996. /**
  35997. * Extracts a clone of a mesh geometry
  35998. * @param mesh defines the source mesh
  35999. * @param id defines the unique ID of the new geometry object
  36000. * @returns the new geometry object
  36001. */
  36002. Geometry.ExtractFromMesh = function (mesh, id) {
  36003. var geometry = mesh._geometry;
  36004. if (!geometry) {
  36005. return null;
  36006. }
  36007. return geometry.copy(id);
  36008. };
  36009. /**
  36010. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  36011. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  36012. * Be aware Math.random() could cause collisions, but:
  36013. * "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"
  36014. * @returns a string containing a new GUID
  36015. */
  36016. Geometry.RandomId = function () {
  36017. return BABYLON.Tools.RandomId();
  36018. };
  36019. /** @ignore */
  36020. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  36021. var scene = mesh.getScene();
  36022. // Geometry
  36023. var geometryId = parsedGeometry.geometryId;
  36024. if (geometryId) {
  36025. var geometry = scene.getGeometryByID(geometryId);
  36026. if (geometry) {
  36027. geometry.applyToMesh(mesh);
  36028. }
  36029. }
  36030. else if (parsedGeometry instanceof ArrayBuffer) {
  36031. var binaryInfo = mesh._binaryInfo;
  36032. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36033. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36034. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36035. }
  36036. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36037. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36038. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36039. }
  36040. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  36041. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  36042. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  36043. }
  36044. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36045. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36046. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36047. }
  36048. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36049. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36050. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36051. }
  36052. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36053. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36054. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36055. }
  36056. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36057. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36058. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36059. }
  36060. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36061. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36062. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36063. }
  36064. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36065. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36066. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36067. }
  36068. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36069. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36070. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36071. }
  36072. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36073. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36074. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36075. }
  36076. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36077. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36078. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36079. }
  36080. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36081. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36082. mesh.setIndices(indicesData, null);
  36083. }
  36084. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36085. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36086. mesh.subMeshes = [];
  36087. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36088. var materialIndex = subMeshesData[(i * 5) + 0];
  36089. var verticesStart = subMeshesData[(i * 5) + 1];
  36090. var verticesCount = subMeshesData[(i * 5) + 2];
  36091. var indexStart = subMeshesData[(i * 5) + 3];
  36092. var indexCount = subMeshesData[(i * 5) + 4];
  36093. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36094. }
  36095. }
  36096. }
  36097. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36098. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  36099. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  36100. if (parsedGeometry.tangents) {
  36101. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  36102. }
  36103. if (parsedGeometry.uvs) {
  36104. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  36105. }
  36106. if (parsedGeometry.uvs2) {
  36107. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  36108. }
  36109. if (parsedGeometry.uvs3) {
  36110. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  36111. }
  36112. if (parsedGeometry.uvs4) {
  36113. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  36114. }
  36115. if (parsedGeometry.uvs5) {
  36116. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  36117. }
  36118. if (parsedGeometry.uvs6) {
  36119. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  36120. }
  36121. if (parsedGeometry.colors) {
  36122. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  36123. }
  36124. if (parsedGeometry.matricesIndices) {
  36125. if (!parsedGeometry.matricesIndices._isExpanded) {
  36126. var floatIndices = [];
  36127. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36128. var matricesIndex = parsedGeometry.matricesIndices[i];
  36129. floatIndices.push(matricesIndex & 0x000000FF);
  36130. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36131. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36132. floatIndices.push(matricesIndex >> 24);
  36133. }
  36134. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  36135. }
  36136. else {
  36137. delete parsedGeometry.matricesIndices._isExpanded;
  36138. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  36139. }
  36140. }
  36141. if (parsedGeometry.matricesIndicesExtra) {
  36142. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36143. var floatIndices = [];
  36144. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36145. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36146. floatIndices.push(matricesIndex & 0x000000FF);
  36147. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36148. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36149. floatIndices.push(matricesIndex >> 24);
  36150. }
  36151. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  36152. }
  36153. else {
  36154. delete parsedGeometry.matricesIndices._isExpanded;
  36155. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  36156. }
  36157. }
  36158. if (parsedGeometry.matricesWeights) {
  36159. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  36160. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  36161. }
  36162. if (parsedGeometry.matricesWeightsExtra) {
  36163. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  36164. }
  36165. mesh.setIndices(parsedGeometry.indices, null);
  36166. }
  36167. // SubMeshes
  36168. if (parsedGeometry.subMeshes) {
  36169. mesh.subMeshes = [];
  36170. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36171. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36172. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36173. }
  36174. }
  36175. // Flat shading
  36176. if (mesh._shouldGenerateFlatShading) {
  36177. mesh.convertToFlatShadedMesh();
  36178. delete mesh._shouldGenerateFlatShading;
  36179. }
  36180. // Update
  36181. mesh.computeWorldMatrix(true);
  36182. // Octree
  36183. var sceneOctree = scene.selectionOctree;
  36184. if (sceneOctree !== undefined && sceneOctree !== null) {
  36185. sceneOctree.addMesh(mesh);
  36186. }
  36187. };
  36188. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  36189. var epsilon = 1e-3;
  36190. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  36191. return;
  36192. }
  36193. var noInfluenceBoneIndex = 0.0;
  36194. if (parsedGeometry.skeletonId > -1) {
  36195. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  36196. if (!skeleton) {
  36197. return;
  36198. }
  36199. noInfluenceBoneIndex = skeleton.bones.length;
  36200. }
  36201. else {
  36202. return;
  36203. }
  36204. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36205. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36206. var matricesWeights = parsedGeometry.matricesWeights;
  36207. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  36208. var influencers = parsedGeometry.numBoneInfluencer;
  36209. var size = matricesWeights.length;
  36210. for (var i = 0; i < size; i += 4) {
  36211. var weight = 0.0;
  36212. var firstZeroWeight = -1;
  36213. for (var j = 0; j < 4; j++) {
  36214. var w = matricesWeights[i + j];
  36215. weight += w;
  36216. if (w < epsilon && firstZeroWeight < 0) {
  36217. firstZeroWeight = j;
  36218. }
  36219. }
  36220. if (matricesWeightsExtra) {
  36221. for (var j = 0; j < 4; j++) {
  36222. var w = matricesWeightsExtra[i + j];
  36223. weight += w;
  36224. if (w < epsilon && firstZeroWeight < 0) {
  36225. firstZeroWeight = j + 4;
  36226. }
  36227. }
  36228. }
  36229. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  36230. firstZeroWeight = influencers - 1;
  36231. }
  36232. if (weight > epsilon) {
  36233. var mweight = 1.0 / weight;
  36234. for (var j = 0; j < 4; j++) {
  36235. matricesWeights[i + j] *= mweight;
  36236. }
  36237. if (matricesWeightsExtra) {
  36238. for (var j = 0; j < 4; j++) {
  36239. matricesWeightsExtra[i + j] *= mweight;
  36240. }
  36241. }
  36242. }
  36243. else {
  36244. if (firstZeroWeight >= 4) {
  36245. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  36246. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  36247. }
  36248. else {
  36249. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  36250. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  36251. }
  36252. }
  36253. }
  36254. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  36255. if (parsedGeometry.matricesWeightsExtra) {
  36256. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  36257. }
  36258. };
  36259. /**
  36260. * Create a new geometry from persisted data (Using .babylon file format)
  36261. * @param parsedVertexData defines the persisted data
  36262. * @param scene defines the hosting scene
  36263. * @param rootUrl defines the root url to use to load assets (like delayed data)
  36264. * @returns the new geometry object
  36265. */
  36266. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36267. if (scene.getGeometryByID(parsedVertexData.id)) {
  36268. return null; // null since geometry could be something else than a box...
  36269. }
  36270. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  36271. if (BABYLON.Tags) {
  36272. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36273. }
  36274. if (parsedVertexData.delayLoadingFile) {
  36275. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36276. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36277. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36278. geometry._delayInfo = [];
  36279. if (parsedVertexData.hasUVs) {
  36280. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36281. }
  36282. if (parsedVertexData.hasUVs2) {
  36283. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36284. }
  36285. if (parsedVertexData.hasUVs3) {
  36286. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36287. }
  36288. if (parsedVertexData.hasUVs4) {
  36289. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36290. }
  36291. if (parsedVertexData.hasUVs5) {
  36292. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36293. }
  36294. if (parsedVertexData.hasUVs6) {
  36295. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36296. }
  36297. if (parsedVertexData.hasColors) {
  36298. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36299. }
  36300. if (parsedVertexData.hasMatricesIndices) {
  36301. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36302. }
  36303. if (parsedVertexData.hasMatricesWeights) {
  36304. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36305. }
  36306. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36307. }
  36308. else {
  36309. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36310. }
  36311. scene.pushGeometry(geometry, true);
  36312. return geometry;
  36313. };
  36314. return Geometry;
  36315. }());
  36316. BABYLON.Geometry = Geometry;
  36317. // Primitives
  36318. /// Abstract class
  36319. /**
  36320. * Abstract class used to provide common services for all typed geometries
  36321. */
  36322. var _PrimitiveGeometry = /** @class */ (function (_super) {
  36323. __extends(_PrimitiveGeometry, _super);
  36324. /**
  36325. * Creates a new typed geometry
  36326. * @param id defines the unique ID of the geometry
  36327. * @param scene defines the hosting scene
  36328. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36329. * @param mesh defines the hosting mesh (can be null)
  36330. */
  36331. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  36332. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  36333. if (mesh === void 0) { mesh = null; }
  36334. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  36335. _this._canBeRegenerated = _canBeRegenerated;
  36336. _this._beingRegenerated = true;
  36337. _this.regenerate();
  36338. _this._beingRegenerated = false;
  36339. return _this;
  36340. }
  36341. /**
  36342. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  36343. * @returns true if the geometry can be regenerated
  36344. */
  36345. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  36346. return this._canBeRegenerated;
  36347. };
  36348. /**
  36349. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  36350. */
  36351. _PrimitiveGeometry.prototype.regenerate = function () {
  36352. if (!this._canBeRegenerated) {
  36353. return;
  36354. }
  36355. this._beingRegenerated = true;
  36356. this.setAllVerticesData(this._regenerateVertexData(), false);
  36357. this._beingRegenerated = false;
  36358. };
  36359. /**
  36360. * Clone the geometry
  36361. * @param id defines the unique ID of the new geometry
  36362. * @returns the new geometry
  36363. */
  36364. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  36365. return _super.prototype.copy.call(this, id);
  36366. };
  36367. // overrides
  36368. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36369. if (!this._beingRegenerated) {
  36370. return;
  36371. }
  36372. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36373. };
  36374. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  36375. if (!this._beingRegenerated) {
  36376. return;
  36377. }
  36378. _super.prototype.setVerticesData.call(this, kind, data, false);
  36379. };
  36380. // to override
  36381. /** @ignore */
  36382. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  36383. throw new Error("Abstract method");
  36384. };
  36385. _PrimitiveGeometry.prototype.copy = function (id) {
  36386. throw new Error("Must be overriden in sub-classes.");
  36387. };
  36388. _PrimitiveGeometry.prototype.serialize = function () {
  36389. var serializationObject = _super.prototype.serialize.call(this);
  36390. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36391. return serializationObject;
  36392. };
  36393. return _PrimitiveGeometry;
  36394. }(Geometry));
  36395. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36396. /**
  36397. * Creates a ribbon geometry
  36398. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36399. */
  36400. var RibbonGeometry = /** @class */ (function (_super) {
  36401. __extends(RibbonGeometry, _super);
  36402. /**
  36403. * Creates a ribbon geometry
  36404. * @param id defines the unique ID of the geometry
  36405. * @param scene defines the hosting scene
  36406. * @param pathArray defines the array of paths to use
  36407. * @param closeArray defines if the last path and the first path must be joined
  36408. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36409. * @param offset defines the offset between points
  36410. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36411. * @param mesh defines the hosting mesh (can be null)
  36412. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36413. */
  36414. function RibbonGeometry(id, scene,
  36415. /**
  36416. * Defines the array of paths to use
  36417. */
  36418. pathArray,
  36419. /**
  36420. * Defines if the last and first points of each path in your pathArray must be joined
  36421. */
  36422. closeArray,
  36423. /**
  36424. * Defines if the last and first points of each path in your pathArray must be joined
  36425. */
  36426. closePath,
  36427. /**
  36428. * Defines the offset between points
  36429. */
  36430. offset, canBeRegenerated, mesh,
  36431. /**
  36432. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36433. */
  36434. side) {
  36435. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36436. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36437. _this.pathArray = pathArray;
  36438. _this.closeArray = closeArray;
  36439. _this.closePath = closePath;
  36440. _this.offset = offset;
  36441. _this.side = side;
  36442. return _this;
  36443. }
  36444. /** @ignore */
  36445. RibbonGeometry.prototype._regenerateVertexData = function () {
  36446. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36447. };
  36448. RibbonGeometry.prototype.copy = function (id) {
  36449. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36450. };
  36451. return RibbonGeometry;
  36452. }(_PrimitiveGeometry));
  36453. BABYLON.RibbonGeometry = RibbonGeometry;
  36454. /**
  36455. * Creates a box geometry
  36456. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36457. */
  36458. var BoxGeometry = /** @class */ (function (_super) {
  36459. __extends(BoxGeometry, _super);
  36460. /**
  36461. * Creates a box geometry
  36462. * @param id defines the unique ID of the geometry
  36463. * @param scene defines the hosting scene
  36464. * @param size defines the zise of the box (width, height and depth are the same)
  36465. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36466. * @param mesh defines the hosting mesh (can be null)
  36467. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36468. */
  36469. function BoxGeometry(id, scene,
  36470. /**
  36471. * Defines the zise of the box (width, height and depth are the same)
  36472. */
  36473. size, canBeRegenerated, mesh,
  36474. /**
  36475. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36476. */
  36477. side) {
  36478. if (mesh === void 0) { mesh = null; }
  36479. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36480. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36481. _this.size = size;
  36482. _this.side = side;
  36483. return _this;
  36484. }
  36485. BoxGeometry.prototype._regenerateVertexData = function () {
  36486. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36487. };
  36488. BoxGeometry.prototype.copy = function (id) {
  36489. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36490. };
  36491. BoxGeometry.prototype.serialize = function () {
  36492. var serializationObject = _super.prototype.serialize.call(this);
  36493. serializationObject.size = this.size;
  36494. return serializationObject;
  36495. };
  36496. BoxGeometry.Parse = function (parsedBox, scene) {
  36497. if (scene.getGeometryByID(parsedBox.id)) {
  36498. return null; // null since geometry could be something else than a box...
  36499. }
  36500. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36501. if (BABYLON.Tags) {
  36502. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36503. }
  36504. scene.pushGeometry(box, true);
  36505. return box;
  36506. };
  36507. return BoxGeometry;
  36508. }(_PrimitiveGeometry));
  36509. BABYLON.BoxGeometry = BoxGeometry;
  36510. /**
  36511. * Creates a sphere geometry
  36512. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36513. */
  36514. var SphereGeometry = /** @class */ (function (_super) {
  36515. __extends(SphereGeometry, _super);
  36516. /**
  36517. * Create a new sphere geometry
  36518. * @param id defines the unique ID of the geometry
  36519. * @param scene defines the hosting scene
  36520. * @param segments defines the number of segments to use to create the sphere
  36521. * @param diameter defines the diameter of the sphere
  36522. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36523. * @param mesh defines the hosting mesh (can be null)
  36524. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36525. */
  36526. function SphereGeometry(id, scene,
  36527. /**
  36528. * Defines the number of segments to use to create the sphere
  36529. */
  36530. segments,
  36531. /**
  36532. * Defines the diameter of the sphere
  36533. */
  36534. diameter, canBeRegenerated, mesh,
  36535. /**
  36536. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36537. */
  36538. side) {
  36539. if (mesh === void 0) { mesh = null; }
  36540. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36541. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36542. _this.segments = segments;
  36543. _this.diameter = diameter;
  36544. _this.side = side;
  36545. return _this;
  36546. }
  36547. SphereGeometry.prototype._regenerateVertexData = function () {
  36548. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36549. };
  36550. SphereGeometry.prototype.copy = function (id) {
  36551. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36552. };
  36553. SphereGeometry.prototype.serialize = function () {
  36554. var serializationObject = _super.prototype.serialize.call(this);
  36555. serializationObject.segments = this.segments;
  36556. serializationObject.diameter = this.diameter;
  36557. return serializationObject;
  36558. };
  36559. SphereGeometry.Parse = function (parsedSphere, scene) {
  36560. if (scene.getGeometryByID(parsedSphere.id)) {
  36561. return null; // null since geometry could be something else than a sphere...
  36562. }
  36563. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36564. if (BABYLON.Tags) {
  36565. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36566. }
  36567. scene.pushGeometry(sphere, true);
  36568. return sphere;
  36569. };
  36570. return SphereGeometry;
  36571. }(_PrimitiveGeometry));
  36572. BABYLON.SphereGeometry = SphereGeometry;
  36573. /**
  36574. * Creates a disc geometry
  36575. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36576. */
  36577. var DiscGeometry = /** @class */ (function (_super) {
  36578. __extends(DiscGeometry, _super);
  36579. /**
  36580. * Creates a new disc geometry
  36581. * @param id defines the unique ID of the geometry
  36582. * @param scene defines the hosting scene
  36583. * @param radius defines the radius of the disc
  36584. * @param tessellation defines the tesselation factor to apply to the disc
  36585. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36586. * @param mesh defines the hosting mesh (can be null)
  36587. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36588. */
  36589. function DiscGeometry(id, scene,
  36590. /**
  36591. * Defines the radius of the disc
  36592. */
  36593. radius,
  36594. /**
  36595. * Defines the tesselation factor to apply to the disc
  36596. */
  36597. tessellation, canBeRegenerated, mesh,
  36598. /**
  36599. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36600. */
  36601. side) {
  36602. if (mesh === void 0) { mesh = null; }
  36603. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36604. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36605. _this.radius = radius;
  36606. _this.tessellation = tessellation;
  36607. _this.side = side;
  36608. return _this;
  36609. }
  36610. DiscGeometry.prototype._regenerateVertexData = function () {
  36611. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36612. };
  36613. DiscGeometry.prototype.copy = function (id) {
  36614. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36615. };
  36616. return DiscGeometry;
  36617. }(_PrimitiveGeometry));
  36618. BABYLON.DiscGeometry = DiscGeometry;
  36619. /**
  36620. * Creates a new cylinder geometry
  36621. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36622. */
  36623. var CylinderGeometry = /** @class */ (function (_super) {
  36624. __extends(CylinderGeometry, _super);
  36625. /**
  36626. * Creates a new cylinder geometry
  36627. * @param id defines the unique ID of the geometry
  36628. * @param scene defines the hosting scene
  36629. * @param height defines the height of the cylinder
  36630. * @param diameterTop defines the diameter of the cylinder's top cap
  36631. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36632. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36633. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36634. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36635. * @param mesh defines the hosting mesh (can be null)
  36636. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36637. */
  36638. function CylinderGeometry(id, scene,
  36639. /**
  36640. * Defines the height of the cylinder
  36641. */
  36642. height,
  36643. /**
  36644. * Defines the diameter of the cylinder's top cap
  36645. */
  36646. diameterTop,
  36647. /**
  36648. * Defines the diameter of the cylinder's bottom cap
  36649. */
  36650. diameterBottom,
  36651. /**
  36652. * Defines the tessellation factor to apply to the cylinder
  36653. */
  36654. tessellation,
  36655. /**
  36656. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36657. */
  36658. subdivisions, canBeRegenerated, mesh,
  36659. /**
  36660. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36661. */
  36662. side) {
  36663. if (subdivisions === void 0) { subdivisions = 1; }
  36664. if (mesh === void 0) { mesh = null; }
  36665. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36666. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36667. _this.height = height;
  36668. _this.diameterTop = diameterTop;
  36669. _this.diameterBottom = diameterBottom;
  36670. _this.tessellation = tessellation;
  36671. _this.subdivisions = subdivisions;
  36672. _this.side = side;
  36673. return _this;
  36674. }
  36675. CylinderGeometry.prototype._regenerateVertexData = function () {
  36676. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36677. };
  36678. CylinderGeometry.prototype.copy = function (id) {
  36679. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36680. };
  36681. CylinderGeometry.prototype.serialize = function () {
  36682. var serializationObject = _super.prototype.serialize.call(this);
  36683. serializationObject.height = this.height;
  36684. serializationObject.diameterTop = this.diameterTop;
  36685. serializationObject.diameterBottom = this.diameterBottom;
  36686. serializationObject.tessellation = this.tessellation;
  36687. return serializationObject;
  36688. };
  36689. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36690. if (scene.getGeometryByID(parsedCylinder.id)) {
  36691. return null; // null since geometry could be something else than a cylinder...
  36692. }
  36693. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36694. if (BABYLON.Tags) {
  36695. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36696. }
  36697. scene.pushGeometry(cylinder, true);
  36698. return cylinder;
  36699. };
  36700. return CylinderGeometry;
  36701. }(_PrimitiveGeometry));
  36702. BABYLON.CylinderGeometry = CylinderGeometry;
  36703. /**
  36704. * Creates a new torus geometry
  36705. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36706. */
  36707. var TorusGeometry = /** @class */ (function (_super) {
  36708. __extends(TorusGeometry, _super);
  36709. /**
  36710. * Creates a new torus geometry
  36711. * @param id defines the unique ID of the geometry
  36712. * @param scene defines the hosting scene
  36713. * @param diameter defines the diameter of the torus
  36714. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36715. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36716. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36717. * @param mesh defines the hosting mesh (can be null)
  36718. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36719. */
  36720. function TorusGeometry(id, scene,
  36721. /**
  36722. * Defines the diameter of the torus
  36723. */
  36724. diameter,
  36725. /**
  36726. * Defines the thickness of the torus (ie. internal diameter)
  36727. */
  36728. thickness,
  36729. /**
  36730. * Defines the tesselation factor to apply to the torus
  36731. */
  36732. tessellation, canBeRegenerated, mesh,
  36733. /**
  36734. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36735. */
  36736. side) {
  36737. if (mesh === void 0) { mesh = null; }
  36738. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36739. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36740. _this.diameter = diameter;
  36741. _this.thickness = thickness;
  36742. _this.tessellation = tessellation;
  36743. _this.side = side;
  36744. return _this;
  36745. }
  36746. TorusGeometry.prototype._regenerateVertexData = function () {
  36747. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36748. };
  36749. TorusGeometry.prototype.copy = function (id) {
  36750. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36751. };
  36752. TorusGeometry.prototype.serialize = function () {
  36753. var serializationObject = _super.prototype.serialize.call(this);
  36754. serializationObject.diameter = this.diameter;
  36755. serializationObject.thickness = this.thickness;
  36756. serializationObject.tessellation = this.tessellation;
  36757. return serializationObject;
  36758. };
  36759. TorusGeometry.Parse = function (parsedTorus, scene) {
  36760. if (scene.getGeometryByID(parsedTorus.id)) {
  36761. return null; // null since geometry could be something else than a torus...
  36762. }
  36763. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36764. if (BABYLON.Tags) {
  36765. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36766. }
  36767. scene.pushGeometry(torus, true);
  36768. return torus;
  36769. };
  36770. return TorusGeometry;
  36771. }(_PrimitiveGeometry));
  36772. BABYLON.TorusGeometry = TorusGeometry;
  36773. /**
  36774. * Creates a new ground geometry
  36775. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36776. */
  36777. var GroundGeometry = /** @class */ (function (_super) {
  36778. __extends(GroundGeometry, _super);
  36779. /**
  36780. * Creates a new ground geometry
  36781. * @param id defines the unique ID of the geometry
  36782. * @param scene defines the hosting scene
  36783. * @param width defines the width of the ground
  36784. * @param height defines the height of the ground
  36785. * @param subdivisions defines the subdivisions to apply to the ground
  36786. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36787. * @param mesh defines the hosting mesh (can be null)
  36788. */
  36789. function GroundGeometry(id, scene,
  36790. /**
  36791. * Defines the width of the ground
  36792. */
  36793. width,
  36794. /**
  36795. * Defines the height of the ground
  36796. */
  36797. height,
  36798. /**
  36799. * Defines the subdivisions to apply to the ground
  36800. */
  36801. subdivisions, canBeRegenerated, mesh) {
  36802. if (mesh === void 0) { mesh = null; }
  36803. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36804. _this.width = width;
  36805. _this.height = height;
  36806. _this.subdivisions = subdivisions;
  36807. return _this;
  36808. }
  36809. GroundGeometry.prototype._regenerateVertexData = function () {
  36810. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36811. };
  36812. GroundGeometry.prototype.copy = function (id) {
  36813. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36814. };
  36815. GroundGeometry.prototype.serialize = function () {
  36816. var serializationObject = _super.prototype.serialize.call(this);
  36817. serializationObject.width = this.width;
  36818. serializationObject.height = this.height;
  36819. serializationObject.subdivisions = this.subdivisions;
  36820. return serializationObject;
  36821. };
  36822. GroundGeometry.Parse = function (parsedGround, scene) {
  36823. if (scene.getGeometryByID(parsedGround.id)) {
  36824. return null; // null since geometry could be something else than a ground...
  36825. }
  36826. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36827. if (BABYLON.Tags) {
  36828. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36829. }
  36830. scene.pushGeometry(ground, true);
  36831. return ground;
  36832. };
  36833. return GroundGeometry;
  36834. }(_PrimitiveGeometry));
  36835. BABYLON.GroundGeometry = GroundGeometry;
  36836. /**
  36837. * Creates a tiled ground geometry
  36838. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36839. */
  36840. var TiledGroundGeometry = /** @class */ (function (_super) {
  36841. __extends(TiledGroundGeometry, _super);
  36842. /**
  36843. * Creates a tiled ground geometry
  36844. * @param id defines the unique ID of the geometry
  36845. * @param scene defines the hosting scene
  36846. * @param xmin defines the minimum value on X axis
  36847. * @param zmin defines the minimum value on Z axis
  36848. * @param xmax defines the maximum value on X axis
  36849. * @param zmax defines the maximum value on Z axis
  36850. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36851. * @param precision defines the precision to use when computing the tiles
  36852. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36853. * @param mesh defines the hosting mesh (can be null)
  36854. */
  36855. function TiledGroundGeometry(id, scene,
  36856. /**
  36857. * Defines the minimum value on X axis
  36858. */
  36859. xmin,
  36860. /**
  36861. * Defines the minimum value on Z axis
  36862. */
  36863. zmin,
  36864. /**
  36865. * Defines the maximum value on X axis
  36866. */
  36867. xmax,
  36868. /**
  36869. * Defines the maximum value on Z axis
  36870. */
  36871. zmax,
  36872. /**
  36873. * Defines the subdivisions to apply to the ground
  36874. */
  36875. subdivisions,
  36876. /**
  36877. * Defines the precision to use when computing the tiles
  36878. */
  36879. precision, canBeRegenerated, mesh) {
  36880. if (mesh === void 0) { mesh = null; }
  36881. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36882. _this.xmin = xmin;
  36883. _this.zmin = zmin;
  36884. _this.xmax = xmax;
  36885. _this.zmax = zmax;
  36886. _this.subdivisions = subdivisions;
  36887. _this.precision = precision;
  36888. return _this;
  36889. }
  36890. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36891. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36892. };
  36893. TiledGroundGeometry.prototype.copy = function (id) {
  36894. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36895. };
  36896. return TiledGroundGeometry;
  36897. }(_PrimitiveGeometry));
  36898. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36899. /**
  36900. * Creates a plane geometry
  36901. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36902. */
  36903. var PlaneGeometry = /** @class */ (function (_super) {
  36904. __extends(PlaneGeometry, _super);
  36905. /**
  36906. * Creates a plane geometry
  36907. * @param id defines the unique ID of the geometry
  36908. * @param scene defines the hosting scene
  36909. * @param size defines the size of the plane (width === height)
  36910. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36911. * @param mesh defines the hosting mesh (can be null)
  36912. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36913. */
  36914. function PlaneGeometry(id, scene,
  36915. /**
  36916. * Defines the size of the plane (width === height)
  36917. */
  36918. size, canBeRegenerated, mesh,
  36919. /**
  36920. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36921. */
  36922. side) {
  36923. if (mesh === void 0) { mesh = null; }
  36924. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36925. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36926. _this.size = size;
  36927. _this.side = side;
  36928. return _this;
  36929. }
  36930. PlaneGeometry.prototype._regenerateVertexData = function () {
  36931. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36932. };
  36933. PlaneGeometry.prototype.copy = function (id) {
  36934. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36935. };
  36936. PlaneGeometry.prototype.serialize = function () {
  36937. var serializationObject = _super.prototype.serialize.call(this);
  36938. serializationObject.size = this.size;
  36939. return serializationObject;
  36940. };
  36941. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36942. if (scene.getGeometryByID(parsedPlane.id)) {
  36943. return null; // null since geometry could be something else than a ground...
  36944. }
  36945. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36946. if (BABYLON.Tags) {
  36947. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36948. }
  36949. scene.pushGeometry(plane, true);
  36950. return plane;
  36951. };
  36952. return PlaneGeometry;
  36953. }(_PrimitiveGeometry));
  36954. BABYLON.PlaneGeometry = PlaneGeometry;
  36955. /**
  36956. * Creates a torus knot geometry
  36957. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36958. */
  36959. var TorusKnotGeometry = /** @class */ (function (_super) {
  36960. __extends(TorusKnotGeometry, _super);
  36961. /**
  36962. * Creates a torus knot geometry
  36963. * @param id defines the unique ID of the geometry
  36964. * @param scene defines the hosting scene
  36965. * @param radius defines the radius of the torus knot
  36966. * @param tube defines the thickness of the torus knot tube
  36967. * @param radialSegments defines the number of radial segments
  36968. * @param tubularSegments defines the number of tubular segments
  36969. * @param p defines the first number of windings
  36970. * @param q defines the second number of windings
  36971. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36972. * @param mesh defines the hosting mesh (can be null)
  36973. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36974. */
  36975. function TorusKnotGeometry(id, scene,
  36976. /**
  36977. * Defines the radius of the torus knot
  36978. */
  36979. radius,
  36980. /**
  36981. * Defines the thickness of the torus knot tube
  36982. */
  36983. tube,
  36984. /**
  36985. * Defines the number of radial segments
  36986. */
  36987. radialSegments,
  36988. /**
  36989. * Defines the number of tubular segments
  36990. */
  36991. tubularSegments,
  36992. /**
  36993. * Defines the first number of windings
  36994. */
  36995. p,
  36996. /**
  36997. * Defines the second number of windings
  36998. */
  36999. q, canBeRegenerated, mesh,
  37000. /**
  37001. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37002. */
  37003. side) {
  37004. if (mesh === void 0) { mesh = null; }
  37005. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37006. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37007. _this.radius = radius;
  37008. _this.tube = tube;
  37009. _this.radialSegments = radialSegments;
  37010. _this.tubularSegments = tubularSegments;
  37011. _this.p = p;
  37012. _this.q = q;
  37013. _this.side = side;
  37014. return _this;
  37015. }
  37016. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  37017. 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 });
  37018. };
  37019. TorusKnotGeometry.prototype.copy = function (id) {
  37020. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  37021. };
  37022. TorusKnotGeometry.prototype.serialize = function () {
  37023. var serializationObject = _super.prototype.serialize.call(this);
  37024. serializationObject.radius = this.radius;
  37025. serializationObject.tube = this.tube;
  37026. serializationObject.radialSegments = this.radialSegments;
  37027. serializationObject.tubularSegments = this.tubularSegments;
  37028. serializationObject.p = this.p;
  37029. serializationObject.q = this.q;
  37030. return serializationObject;
  37031. };
  37032. ;
  37033. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  37034. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37035. return null; // null since geometry could be something else than a ground...
  37036. }
  37037. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37038. if (BABYLON.Tags) {
  37039. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37040. }
  37041. scene.pushGeometry(torusKnot, true);
  37042. return torusKnot;
  37043. };
  37044. return TorusKnotGeometry;
  37045. }(_PrimitiveGeometry));
  37046. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  37047. //}
  37048. })(BABYLON || (BABYLON = {}));
  37049. //# sourceMappingURL=babylon.geometry.js.map
  37050. "use strict";
  37051. var BABYLON;
  37052. (function (BABYLON) {
  37053. /**
  37054. * PostProcessManager is used to manage one or more post processes or post process pipelines
  37055. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  37056. */
  37057. var PostProcessManager = /** @class */ (function () {
  37058. /**
  37059. * Creates a new instance of @see PostProcess
  37060. * @param scene The scene that the post process is associated with.
  37061. */
  37062. function PostProcessManager(scene) {
  37063. this._vertexBuffers = {};
  37064. this._scene = scene;
  37065. }
  37066. PostProcessManager.prototype._prepareBuffers = function () {
  37067. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  37068. return;
  37069. }
  37070. // VBO
  37071. var vertices = [];
  37072. vertices.push(1, 1);
  37073. vertices.push(-1, 1);
  37074. vertices.push(-1, -1);
  37075. vertices.push(1, -1);
  37076. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37077. this._buildIndexBuffer();
  37078. };
  37079. PostProcessManager.prototype._buildIndexBuffer = function () {
  37080. // Indices
  37081. var indices = [];
  37082. indices.push(0);
  37083. indices.push(1);
  37084. indices.push(2);
  37085. indices.push(0);
  37086. indices.push(2);
  37087. indices.push(3);
  37088. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  37089. };
  37090. /**
  37091. * Rebuilds the vertex buffers of the manager.
  37092. */
  37093. PostProcessManager.prototype._rebuild = function () {
  37094. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37095. if (!vb) {
  37096. return;
  37097. }
  37098. vb._rebuild();
  37099. this._buildIndexBuffer();
  37100. };
  37101. // Methods
  37102. /**
  37103. * Prepares a frame to be run through a post process.
  37104. * @param sourceTexture The input texture to the post procesess. (default: null)
  37105. * @param postProcesses An array of post processes to be run. (default: null)
  37106. * @returns True if the post processes were able to be run.
  37107. */
  37108. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  37109. if (sourceTexture === void 0) { sourceTexture = null; }
  37110. if (postProcesses === void 0) { postProcesses = null; }
  37111. var camera = this._scene.activeCamera;
  37112. if (!camera) {
  37113. return false;
  37114. }
  37115. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37116. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37117. return false;
  37118. }
  37119. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  37120. return true;
  37121. };
  37122. /**
  37123. * Manually render a set of post processes to a texture.
  37124. * @param postProcesses An array of post processes to be run.
  37125. * @param targetTexture The target texture to render to.
  37126. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  37127. */
  37128. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  37129. if (targetTexture === void 0) { targetTexture = null; }
  37130. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37131. var engine = this._scene.getEngine();
  37132. for (var index = 0; index < postProcesses.length; index++) {
  37133. if (index < postProcesses.length - 1) {
  37134. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  37135. }
  37136. else {
  37137. if (targetTexture) {
  37138. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  37139. }
  37140. else {
  37141. engine.restoreDefaultFramebuffer();
  37142. }
  37143. }
  37144. var pp = postProcesses[index];
  37145. var effect = pp.apply();
  37146. if (effect) {
  37147. pp.onBeforeRenderObservable.notifyObservers(effect);
  37148. // VBOs
  37149. this._prepareBuffers();
  37150. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37151. // Draw order
  37152. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37153. pp.onAfterRenderObservable.notifyObservers(effect);
  37154. }
  37155. }
  37156. // Restore depth buffer
  37157. engine.setDepthBuffer(true);
  37158. engine.setDepthWrite(true);
  37159. };
  37160. /**
  37161. * Finalize the result of the output of the postprocesses.
  37162. * @param doNotPresent If true the result will not be displayed to the screen.
  37163. * @param targetTexture The target texture to render to.
  37164. * @param faceIndex The index of the face to bind the target texture to.
  37165. * @param postProcesses The array of post processes to render.
  37166. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  37167. */
  37168. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  37169. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37170. var camera = this._scene.activeCamera;
  37171. if (!camera) {
  37172. return;
  37173. }
  37174. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37175. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37176. return;
  37177. }
  37178. var engine = this._scene.getEngine();
  37179. for (var index = 0, len = postProcesses.length; index < len; index++) {
  37180. var pp = postProcesses[index];
  37181. if (index < len - 1) {
  37182. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  37183. }
  37184. else {
  37185. if (targetTexture) {
  37186. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  37187. }
  37188. else {
  37189. engine.restoreDefaultFramebuffer();
  37190. }
  37191. }
  37192. if (doNotPresent) {
  37193. break;
  37194. }
  37195. var effect = pp.apply();
  37196. if (effect) {
  37197. pp.onBeforeRenderObservable.notifyObservers(effect);
  37198. // VBOs
  37199. this._prepareBuffers();
  37200. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37201. // Draw order
  37202. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37203. pp.onAfterRenderObservable.notifyObservers(effect);
  37204. }
  37205. }
  37206. // Restore states
  37207. engine.setDepthBuffer(true);
  37208. engine.setDepthWrite(true);
  37209. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37210. };
  37211. /**
  37212. * Disposes of the post process manager.
  37213. */
  37214. PostProcessManager.prototype.dispose = function () {
  37215. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37216. if (buffer) {
  37217. buffer.dispose();
  37218. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37219. }
  37220. if (this._indexBuffer) {
  37221. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37222. this._indexBuffer = null;
  37223. }
  37224. };
  37225. return PostProcessManager;
  37226. }());
  37227. BABYLON.PostProcessManager = PostProcessManager;
  37228. })(BABYLON || (BABYLON = {}));
  37229. //# sourceMappingURL=babylon.postProcessManager.js.map
  37230. "use strict";
  37231. var BABYLON;
  37232. (function (BABYLON) {
  37233. /**
  37234. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  37235. */
  37236. var PerformanceMonitor = /** @class */ (function () {
  37237. /**
  37238. * constructor
  37239. * @param frameSampleSize The number of samples required to saturate the sliding window
  37240. */
  37241. function PerformanceMonitor(frameSampleSize) {
  37242. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  37243. this._enabled = true;
  37244. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  37245. }
  37246. /**
  37247. * Samples current frame
  37248. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  37249. */
  37250. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  37251. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  37252. if (!this._enabled)
  37253. return;
  37254. if (this._lastFrameTimeMs != null) {
  37255. var dt = timeMs - this._lastFrameTimeMs;
  37256. this._rollingFrameTime.add(dt);
  37257. }
  37258. this._lastFrameTimeMs = timeMs;
  37259. };
  37260. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  37261. /**
  37262. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37263. * @return Average frame time in milliseconds
  37264. */
  37265. get: function () {
  37266. return this._rollingFrameTime.average;
  37267. },
  37268. enumerable: true,
  37269. configurable: true
  37270. });
  37271. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  37272. /**
  37273. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37274. * @return Frame time variance in milliseconds squared
  37275. */
  37276. get: function () {
  37277. return this._rollingFrameTime.variance;
  37278. },
  37279. enumerable: true,
  37280. configurable: true
  37281. });
  37282. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  37283. /**
  37284. * Returns the frame time of the most recent frame
  37285. * @return Frame time in milliseconds
  37286. */
  37287. get: function () {
  37288. return this._rollingFrameTime.history(0);
  37289. },
  37290. enumerable: true,
  37291. configurable: true
  37292. });
  37293. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  37294. /**
  37295. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  37296. * @return Framerate in frames per second
  37297. */
  37298. get: function () {
  37299. return 1000.0 / this._rollingFrameTime.average;
  37300. },
  37301. enumerable: true,
  37302. configurable: true
  37303. });
  37304. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  37305. /**
  37306. * Returns the average framerate in frames per second using the most recent frame time
  37307. * @return Framerate in frames per second
  37308. */
  37309. get: function () {
  37310. var history = this._rollingFrameTime.history(0);
  37311. if (history === 0) {
  37312. return 0;
  37313. }
  37314. return 1000.0 / history;
  37315. },
  37316. enumerable: true,
  37317. configurable: true
  37318. });
  37319. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  37320. /**
  37321. * Returns true if enough samples have been taken to completely fill the sliding window
  37322. * @return true if saturated
  37323. */
  37324. get: function () {
  37325. return this._rollingFrameTime.isSaturated();
  37326. },
  37327. enumerable: true,
  37328. configurable: true
  37329. });
  37330. /**
  37331. * Enables contributions to the sliding window sample set
  37332. */
  37333. PerformanceMonitor.prototype.enable = function () {
  37334. this._enabled = true;
  37335. };
  37336. /**
  37337. * Disables contributions to the sliding window sample set
  37338. * Samples will not be interpolated over the disabled period
  37339. */
  37340. PerformanceMonitor.prototype.disable = function () {
  37341. this._enabled = false;
  37342. //clear last sample to avoid interpolating over the disabled period when next enabled
  37343. this._lastFrameTimeMs = null;
  37344. };
  37345. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  37346. /**
  37347. * Returns true if sampling is enabled
  37348. * @return true if enabled
  37349. */
  37350. get: function () {
  37351. return this._enabled;
  37352. },
  37353. enumerable: true,
  37354. configurable: true
  37355. });
  37356. /**
  37357. * Resets performance monitor
  37358. */
  37359. PerformanceMonitor.prototype.reset = function () {
  37360. //clear last sample to avoid interpolating over the disabled period when next enabled
  37361. this._lastFrameTimeMs = null;
  37362. //wipe record
  37363. this._rollingFrameTime.reset();
  37364. };
  37365. return PerformanceMonitor;
  37366. }());
  37367. BABYLON.PerformanceMonitor = PerformanceMonitor;
  37368. /**
  37369. * RollingAverage
  37370. *
  37371. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  37372. */
  37373. var RollingAverage = /** @class */ (function () {
  37374. /**
  37375. * constructor
  37376. * @param length The number of samples required to saturate the sliding window
  37377. */
  37378. function RollingAverage(length) {
  37379. this._samples = new Array(length);
  37380. this.reset();
  37381. }
  37382. /**
  37383. * Adds a sample to the sample set
  37384. * @param v The sample value
  37385. */
  37386. RollingAverage.prototype.add = function (v) {
  37387. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  37388. var delta;
  37389. //we need to check if we've already wrapped round
  37390. if (this.isSaturated()) {
  37391. //remove bottom of stack from mean
  37392. var bottomValue = this._samples[this._pos];
  37393. delta = bottomValue - this.average;
  37394. this.average -= delta / (this._sampleCount - 1);
  37395. this._m2 -= delta * (bottomValue - this.average);
  37396. }
  37397. else {
  37398. this._sampleCount++;
  37399. }
  37400. //add new value to mean
  37401. delta = v - this.average;
  37402. this.average += delta / (this._sampleCount);
  37403. this._m2 += delta * (v - this.average);
  37404. //set the new variance
  37405. this.variance = this._m2 / (this._sampleCount - 1);
  37406. this._samples[this._pos] = v;
  37407. this._pos++;
  37408. this._pos %= this._samples.length; //positive wrap around
  37409. };
  37410. /**
  37411. * Returns previously added values or null if outside of history or outside the sliding window domain
  37412. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37413. * @return Value previously recorded with add() or null if outside of range
  37414. */
  37415. RollingAverage.prototype.history = function (i) {
  37416. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37417. return 0;
  37418. }
  37419. var i0 = this._wrapPosition(this._pos - 1.0);
  37420. return this._samples[this._wrapPosition(i0 - i)];
  37421. };
  37422. /**
  37423. * Returns true if enough samples have been taken to completely fill the sliding window
  37424. * @return true if sample-set saturated
  37425. */
  37426. RollingAverage.prototype.isSaturated = function () {
  37427. return this._sampleCount >= this._samples.length;
  37428. };
  37429. /**
  37430. * Resets the rolling average (equivalent to 0 samples taken so far)
  37431. */
  37432. RollingAverage.prototype.reset = function () {
  37433. this.average = 0;
  37434. this.variance = 0;
  37435. this._sampleCount = 0;
  37436. this._pos = 0;
  37437. this._m2 = 0;
  37438. };
  37439. /**
  37440. * Wraps a value around the sample range boundaries
  37441. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37442. * @return Wrapped position in sample range
  37443. */
  37444. RollingAverage.prototype._wrapPosition = function (i) {
  37445. var max = this._samples.length;
  37446. return ((i % max) + max) % max;
  37447. };
  37448. return RollingAverage;
  37449. }());
  37450. BABYLON.RollingAverage = RollingAverage;
  37451. })(BABYLON || (BABYLON = {}));
  37452. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37453. "use strict";
  37454. var BABYLON;
  37455. (function (BABYLON) {
  37456. /**
  37457. * This groups together the common properties used for image processing either in direct forward pass
  37458. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37459. * or not.
  37460. */
  37461. var ImageProcessingConfiguration = /** @class */ (function () {
  37462. function ImageProcessingConfiguration() {
  37463. /**
  37464. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37465. */
  37466. this.colorCurves = new BABYLON.ColorCurves();
  37467. this._colorCurvesEnabled = false;
  37468. this._colorGradingEnabled = false;
  37469. this._colorGradingWithGreenDepth = true;
  37470. this._colorGradingBGR = true;
  37471. this._exposure = 1.0;
  37472. this._toneMappingEnabled = false;
  37473. this._contrast = 1.0;
  37474. /**
  37475. * Vignette stretch size.
  37476. */
  37477. this.vignetteStretch = 0;
  37478. /**
  37479. * Vignette centre X Offset.
  37480. */
  37481. this.vignetteCentreX = 0;
  37482. /**
  37483. * Vignette centre Y Offset.
  37484. */
  37485. this.vignetteCentreY = 0;
  37486. /**
  37487. * Vignette weight or intensity of the vignette effect.
  37488. */
  37489. this.vignetteWeight = 1.5;
  37490. /**
  37491. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37492. * if vignetteEnabled is set to true.
  37493. */
  37494. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37495. /**
  37496. * Camera field of view used by the Vignette effect.
  37497. */
  37498. this.vignetteCameraFov = 0.5;
  37499. this._grainEnabled = false;
  37500. this._grainIntensity = 30;
  37501. this._grainAnimated = false;
  37502. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37503. this._vignetteEnabled = false;
  37504. this._applyByPostProcess = false;
  37505. this._isEnabled = true;
  37506. /**
  37507. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37508. * @type {BABYLON.Observable}
  37509. */
  37510. this.onUpdateParameters = new BABYLON.Observable();
  37511. }
  37512. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37513. /**
  37514. * Gets wether the color curves effect is enabled.
  37515. */
  37516. get: function () {
  37517. return this._colorCurvesEnabled;
  37518. },
  37519. /**
  37520. * Sets wether the color curves effect is enabled.
  37521. */
  37522. set: function (value) {
  37523. if (this._colorCurvesEnabled === value) {
  37524. return;
  37525. }
  37526. this._colorCurvesEnabled = value;
  37527. this._updateParameters();
  37528. },
  37529. enumerable: true,
  37530. configurable: true
  37531. });
  37532. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37533. /**
  37534. * Gets wether the color grading effect is enabled.
  37535. */
  37536. get: function () {
  37537. return this._colorGradingEnabled;
  37538. },
  37539. /**
  37540. * Sets wether the color grading effect is enabled.
  37541. */
  37542. set: function (value) {
  37543. if (this._colorGradingEnabled === value) {
  37544. return;
  37545. }
  37546. this._colorGradingEnabled = value;
  37547. this._updateParameters();
  37548. },
  37549. enumerable: true,
  37550. configurable: true
  37551. });
  37552. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37553. /**
  37554. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37555. */
  37556. get: function () {
  37557. return this._colorGradingWithGreenDepth;
  37558. },
  37559. /**
  37560. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37561. */
  37562. set: function (value) {
  37563. if (this._colorGradingWithGreenDepth === value) {
  37564. return;
  37565. }
  37566. this._colorGradingWithGreenDepth = value;
  37567. this._updateParameters();
  37568. },
  37569. enumerable: true,
  37570. configurable: true
  37571. });
  37572. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37573. /**
  37574. * Gets wether the color grading texture contains BGR values.
  37575. */
  37576. get: function () {
  37577. return this._colorGradingBGR;
  37578. },
  37579. /**
  37580. * Sets wether the color grading texture contains BGR values.
  37581. */
  37582. set: function (value) {
  37583. if (this._colorGradingBGR === value) {
  37584. return;
  37585. }
  37586. this._colorGradingBGR = value;
  37587. this._updateParameters();
  37588. },
  37589. enumerable: true,
  37590. configurable: true
  37591. });
  37592. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37593. /**
  37594. * Gets the Exposure used in the effect.
  37595. */
  37596. get: function () {
  37597. return this._exposure;
  37598. },
  37599. /**
  37600. * Sets the Exposure used in the effect.
  37601. */
  37602. set: function (value) {
  37603. if (this._exposure === value) {
  37604. return;
  37605. }
  37606. this._exposure = value;
  37607. this._updateParameters();
  37608. },
  37609. enumerable: true,
  37610. configurable: true
  37611. });
  37612. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37613. /**
  37614. * Gets wether the tone mapping effect is enabled.
  37615. */
  37616. get: function () {
  37617. return this._toneMappingEnabled;
  37618. },
  37619. /**
  37620. * Sets wether the tone mapping effect is enabled.
  37621. */
  37622. set: function (value) {
  37623. if (this._toneMappingEnabled === value) {
  37624. return;
  37625. }
  37626. this._toneMappingEnabled = value;
  37627. this._updateParameters();
  37628. },
  37629. enumerable: true,
  37630. configurable: true
  37631. });
  37632. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37633. /**
  37634. * Gets the contrast used in the effect.
  37635. */
  37636. get: function () {
  37637. return this._contrast;
  37638. },
  37639. /**
  37640. * Sets the contrast used in the effect.
  37641. */
  37642. set: function (value) {
  37643. if (this._contrast === value) {
  37644. return;
  37645. }
  37646. this._contrast = value;
  37647. this._updateParameters();
  37648. },
  37649. enumerable: true,
  37650. configurable: true
  37651. });
  37652. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37653. /**
  37654. * If the grain effect should be enabled.
  37655. */
  37656. get: function () {
  37657. return this._grainEnabled;
  37658. },
  37659. set: function (value) {
  37660. if (this._grainEnabled === value) {
  37661. return;
  37662. }
  37663. this._grainEnabled = value;
  37664. this._updateParameters();
  37665. },
  37666. enumerable: true,
  37667. configurable: true
  37668. });
  37669. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37670. /**
  37671. * Amount of grain to be applied by the grain effect.
  37672. */
  37673. get: function () {
  37674. return this._grainIntensity;
  37675. },
  37676. set: function (value) {
  37677. if (this._grainIntensity === value) {
  37678. return;
  37679. }
  37680. this._grainIntensity = value;
  37681. },
  37682. enumerable: true,
  37683. configurable: true
  37684. });
  37685. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37686. /**
  37687. * If the grain effect should be animated.
  37688. */
  37689. get: function () {
  37690. return this._grainAnimated;
  37691. },
  37692. set: function (value) {
  37693. if (this._grainAnimated === value) {
  37694. return;
  37695. }
  37696. this._grainAnimated = value;
  37697. this._updateParameters();
  37698. },
  37699. enumerable: true,
  37700. configurable: true
  37701. });
  37702. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37703. /**
  37704. * Gets the vignette blend mode allowing different kind of effect.
  37705. */
  37706. get: function () {
  37707. return this._vignetteBlendMode;
  37708. },
  37709. /**
  37710. * Sets the vignette blend mode allowing different kind of effect.
  37711. */
  37712. set: function (value) {
  37713. if (this._vignetteBlendMode === value) {
  37714. return;
  37715. }
  37716. this._vignetteBlendMode = value;
  37717. this._updateParameters();
  37718. },
  37719. enumerable: true,
  37720. configurable: true
  37721. });
  37722. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37723. /**
  37724. * Gets wether the vignette effect is enabled.
  37725. */
  37726. get: function () {
  37727. return this._vignetteEnabled;
  37728. },
  37729. /**
  37730. * Sets wether the vignette effect is enabled.
  37731. */
  37732. set: function (value) {
  37733. if (this._vignetteEnabled === value) {
  37734. return;
  37735. }
  37736. this._vignetteEnabled = value;
  37737. this._updateParameters();
  37738. },
  37739. enumerable: true,
  37740. configurable: true
  37741. });
  37742. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37743. /**
  37744. * Gets wether the image processing is applied through a post process or not.
  37745. */
  37746. get: function () {
  37747. return this._applyByPostProcess;
  37748. },
  37749. /**
  37750. * Sets wether the image processing is applied through a post process or not.
  37751. */
  37752. set: function (value) {
  37753. if (this._applyByPostProcess === value) {
  37754. return;
  37755. }
  37756. this._applyByPostProcess = value;
  37757. this._updateParameters();
  37758. },
  37759. enumerable: true,
  37760. configurable: true
  37761. });
  37762. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37763. /**
  37764. * Gets wether the image processing is enabled or not.
  37765. */
  37766. get: function () {
  37767. return this._isEnabled;
  37768. },
  37769. /**
  37770. * Sets wether the image processing is enabled or not.
  37771. */
  37772. set: function (value) {
  37773. if (this._isEnabled === value) {
  37774. return;
  37775. }
  37776. this._isEnabled = value;
  37777. this._updateParameters();
  37778. },
  37779. enumerable: true,
  37780. configurable: true
  37781. });
  37782. /**
  37783. * Method called each time the image processing information changes requires to recompile the effect.
  37784. */
  37785. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37786. this.onUpdateParameters.notifyObservers(this);
  37787. };
  37788. ImageProcessingConfiguration.prototype.getClassName = function () {
  37789. return "ImageProcessingConfiguration";
  37790. };
  37791. /**
  37792. * Prepare the list of uniforms associated with the Image Processing effects.
  37793. * @param uniformsList The list of uniforms used in the effect
  37794. * @param defines the list of defines currently in use
  37795. */
  37796. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37797. if (defines.EXPOSURE) {
  37798. uniforms.push("exposureLinear");
  37799. }
  37800. if (defines.CONTRAST) {
  37801. uniforms.push("contrast");
  37802. }
  37803. if (defines.COLORGRADING) {
  37804. uniforms.push("colorTransformSettings");
  37805. }
  37806. if (defines.VIGNETTE) {
  37807. uniforms.push("vInverseScreenSize");
  37808. uniforms.push("vignetteSettings1");
  37809. uniforms.push("vignetteSettings2");
  37810. }
  37811. if (defines.COLORCURVES) {
  37812. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37813. }
  37814. if (defines.GRAIN) {
  37815. uniforms.push("grainVarianceAmount");
  37816. uniforms.push("grainAnimatedSeed");
  37817. }
  37818. };
  37819. /**
  37820. * Prepare the list of samplers associated with the Image Processing effects.
  37821. * @param uniformsList The list of uniforms used in the effect
  37822. * @param defines the list of defines currently in use
  37823. */
  37824. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37825. if (defines.COLORGRADING) {
  37826. samplersList.push("txColorTransform");
  37827. }
  37828. };
  37829. /**
  37830. * Prepare the list of defines associated to the shader.
  37831. * @param defines the list of defines to complete
  37832. */
  37833. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37834. if (forPostProcess === void 0) { forPostProcess = false; }
  37835. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37836. defines.VIGNETTE = false;
  37837. defines.TONEMAPPING = false;
  37838. defines.CONTRAST = false;
  37839. defines.EXPOSURE = false;
  37840. defines.COLORCURVES = false;
  37841. defines.COLORGRADING = false;
  37842. defines.COLORGRADING3D = false;
  37843. defines.IMAGEPROCESSING = false;
  37844. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37845. return;
  37846. }
  37847. defines.VIGNETTE = this.vignetteEnabled;
  37848. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37849. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37850. defines.TONEMAPPING = this.toneMappingEnabled;
  37851. defines.CONTRAST = (this.contrast !== 1.0);
  37852. defines.EXPOSURE = (this.exposure !== 1.0);
  37853. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37854. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37855. if (defines.COLORGRADING) {
  37856. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37857. }
  37858. else {
  37859. defines.COLORGRADING3D = false;
  37860. }
  37861. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37862. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37863. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37864. defines.GRAIN = this.grainEnabled;
  37865. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37866. };
  37867. /**
  37868. * Returns true if all the image processing information are ready.
  37869. */
  37870. ImageProcessingConfiguration.prototype.isReady = function () {
  37871. // Color Grading texure can not be none blocking.
  37872. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37873. };
  37874. /**
  37875. * Binds the image processing to the shader.
  37876. * @param effect The effect to bind to
  37877. */
  37878. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37879. if (aspectRatio === void 0) { aspectRatio = 1; }
  37880. // Color Curves
  37881. if (this._colorCurvesEnabled && this.colorCurves) {
  37882. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37883. }
  37884. // Vignette
  37885. if (this._vignetteEnabled) {
  37886. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37887. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37888. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37889. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37890. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37891. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37892. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37893. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37894. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37895. var vignettePower = -2.0 * this.vignetteWeight;
  37896. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37897. }
  37898. // Exposure
  37899. effect.setFloat("exposureLinear", this.exposure);
  37900. // Contrast
  37901. effect.setFloat("contrast", this.contrast);
  37902. // Color transform settings
  37903. if (this.colorGradingTexture) {
  37904. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37905. var textureSize = this.colorGradingTexture.getSize().height;
  37906. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37907. 0.5 / textureSize, // textureOffset
  37908. textureSize, // textureSize
  37909. this.colorGradingTexture.level // weight
  37910. );
  37911. }
  37912. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37913. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37914. };
  37915. /**
  37916. * Clones the current image processing instance.
  37917. * @return The cloned image processing
  37918. */
  37919. ImageProcessingConfiguration.prototype.clone = function () {
  37920. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37921. };
  37922. /**
  37923. * Serializes the current image processing instance to a json representation.
  37924. * @return a JSON representation
  37925. */
  37926. ImageProcessingConfiguration.prototype.serialize = function () {
  37927. return BABYLON.SerializationHelper.Serialize(this);
  37928. };
  37929. /**
  37930. * Parses the image processing from a json representation.
  37931. * @param source the JSON source to parse
  37932. * @return The parsed image processing
  37933. */
  37934. ImageProcessingConfiguration.Parse = function (source) {
  37935. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37936. };
  37937. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37938. /**
  37939. * Used to apply the vignette as a mix with the pixel color.
  37940. */
  37941. get: function () {
  37942. return this._VIGNETTEMODE_MULTIPLY;
  37943. },
  37944. enumerable: true,
  37945. configurable: true
  37946. });
  37947. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37948. /**
  37949. * Used to apply the vignette as a replacement of the pixel color.
  37950. */
  37951. get: function () {
  37952. return this._VIGNETTEMODE_OPAQUE;
  37953. },
  37954. enumerable: true,
  37955. configurable: true
  37956. });
  37957. // Static constants associated to the image processing.
  37958. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37959. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37960. __decorate([
  37961. BABYLON.serializeAsColorCurves()
  37962. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37963. __decorate([
  37964. BABYLON.serialize()
  37965. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37966. __decorate([
  37967. BABYLON.serializeAsTexture()
  37968. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37969. __decorate([
  37970. BABYLON.serialize()
  37971. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37972. __decorate([
  37973. BABYLON.serialize()
  37974. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37975. __decorate([
  37976. BABYLON.serialize()
  37977. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37978. __decorate([
  37979. BABYLON.serialize()
  37980. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37981. __decorate([
  37982. BABYLON.serialize()
  37983. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37984. __decorate([
  37985. BABYLON.serialize()
  37986. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37987. __decorate([
  37988. BABYLON.serialize()
  37989. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37990. __decorate([
  37991. BABYLON.serialize()
  37992. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37993. __decorate([
  37994. BABYLON.serialize()
  37995. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37996. __decorate([
  37997. BABYLON.serialize()
  37998. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37999. __decorate([
  38000. BABYLON.serializeAsColor4()
  38001. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  38002. __decorate([
  38003. BABYLON.serialize()
  38004. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  38005. __decorate([
  38006. BABYLON.serialize()
  38007. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  38008. __decorate([
  38009. BABYLON.serialize()
  38010. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  38011. __decorate([
  38012. BABYLON.serialize()
  38013. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  38014. __decorate([
  38015. BABYLON.serialize()
  38016. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  38017. __decorate([
  38018. BABYLON.serialize()
  38019. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  38020. __decorate([
  38021. BABYLON.serialize()
  38022. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  38023. __decorate([
  38024. BABYLON.serialize()
  38025. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  38026. return ImageProcessingConfiguration;
  38027. }());
  38028. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  38029. })(BABYLON || (BABYLON = {}));
  38030. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  38031. "use strict";
  38032. var BABYLON;
  38033. (function (BABYLON) {
  38034. /**
  38035. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  38036. * It can help converting any input color in a desired output one. This can then be used to create effects
  38037. * from sepia, black and white to sixties or futuristic rendering...
  38038. *
  38039. * The only supported format is currently 3dl.
  38040. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  38041. */
  38042. var ColorGradingTexture = /** @class */ (function (_super) {
  38043. __extends(ColorGradingTexture, _super);
  38044. /**
  38045. * Instantiates a ColorGradingTexture from the following parameters.
  38046. *
  38047. * @param url The location of the color gradind data (currently only supporting 3dl)
  38048. * @param scene The scene the texture will be used in
  38049. */
  38050. function ColorGradingTexture(url, scene) {
  38051. var _this = _super.call(this, scene) || this;
  38052. if (!url) {
  38053. return _this;
  38054. }
  38055. _this._engine = scene.getEngine();
  38056. _this._textureMatrix = BABYLON.Matrix.Identity();
  38057. _this.name = url;
  38058. _this.url = url;
  38059. _this.hasAlpha = false;
  38060. _this.isCube = false;
  38061. _this.is3D = _this._engine.webGLVersion > 1;
  38062. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38063. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38064. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38065. _this.anisotropicFilteringLevel = 1;
  38066. _this._texture = _this._getFromCache(url, true);
  38067. if (!_this._texture) {
  38068. if (!scene.useDelayedTextureLoading) {
  38069. _this.loadTexture();
  38070. }
  38071. else {
  38072. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38073. }
  38074. }
  38075. return _this;
  38076. }
  38077. /**
  38078. * Returns the texture matrix used in most of the material.
  38079. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  38080. */
  38081. ColorGradingTexture.prototype.getTextureMatrix = function () {
  38082. return this._textureMatrix;
  38083. };
  38084. /**
  38085. * Occurs when the file being loaded is a .3dl LUT file.
  38086. */
  38087. ColorGradingTexture.prototype.load3dlTexture = function () {
  38088. var engine = this._engine;
  38089. var texture;
  38090. if (engine.webGLVersion === 1) {
  38091. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38092. }
  38093. else {
  38094. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38095. }
  38096. this._texture = texture;
  38097. var callback = function (text) {
  38098. if (typeof text !== "string") {
  38099. return;
  38100. }
  38101. var data = null;
  38102. var tempData = null;
  38103. var line;
  38104. var lines = text.split('\n');
  38105. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  38106. var maxColor = 0;
  38107. for (var i = 0; i < lines.length; i++) {
  38108. line = lines[i];
  38109. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  38110. continue;
  38111. if (line.indexOf('#') === 0)
  38112. continue;
  38113. var words = line.split(" ");
  38114. if (size === 0) {
  38115. // Number of space + one
  38116. size = words.length;
  38117. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  38118. tempData = new Float32Array(size * size * size * 4);
  38119. continue;
  38120. }
  38121. if (size != 0) {
  38122. var r = Math.max(parseInt(words[0]), 0);
  38123. var g = Math.max(parseInt(words[1]), 0);
  38124. var b = Math.max(parseInt(words[2]), 0);
  38125. maxColor = Math.max(r, maxColor);
  38126. maxColor = Math.max(g, maxColor);
  38127. maxColor = Math.max(b, maxColor);
  38128. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  38129. if (tempData) {
  38130. tempData[pixelStorageIndex + 0] = r;
  38131. tempData[pixelStorageIndex + 1] = g;
  38132. tempData[pixelStorageIndex + 2] = b;
  38133. }
  38134. pixelIndexSlice++;
  38135. if (pixelIndexSlice % size == 0) {
  38136. pixelIndexH++;
  38137. pixelIndexSlice = 0;
  38138. if (pixelIndexH % size == 0) {
  38139. pixelIndexW++;
  38140. pixelIndexH = 0;
  38141. }
  38142. }
  38143. }
  38144. }
  38145. if (tempData && data) {
  38146. for (var i = 0; i < tempData.length; i++) {
  38147. if (i > 0 && (i + 1) % 4 === 0) {
  38148. data[i] = 255;
  38149. }
  38150. else {
  38151. var value = tempData[i];
  38152. data[i] = (value / maxColor * 255);
  38153. }
  38154. }
  38155. }
  38156. if (texture.is3D) {
  38157. texture.updateSize(size, size, size);
  38158. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38159. }
  38160. else {
  38161. texture.updateSize(size * size, size);
  38162. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38163. }
  38164. };
  38165. var scene = this.getScene();
  38166. if (scene) {
  38167. scene._loadFile(this.url, callback);
  38168. }
  38169. else {
  38170. this._engine._loadFile(this.url, callback);
  38171. }
  38172. return this._texture;
  38173. };
  38174. /**
  38175. * Starts the loading process of the texture.
  38176. */
  38177. ColorGradingTexture.prototype.loadTexture = function () {
  38178. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  38179. this.load3dlTexture();
  38180. }
  38181. };
  38182. /**
  38183. * Clones the color gradind texture.
  38184. */
  38185. ColorGradingTexture.prototype.clone = function () {
  38186. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  38187. // Base texture
  38188. newTexture.level = this.level;
  38189. return newTexture;
  38190. };
  38191. /**
  38192. * Called during delayed load for textures.
  38193. */
  38194. ColorGradingTexture.prototype.delayLoad = function () {
  38195. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38196. return;
  38197. }
  38198. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38199. this._texture = this._getFromCache(this.url, true);
  38200. if (!this._texture) {
  38201. this.loadTexture();
  38202. }
  38203. };
  38204. /**
  38205. * Parses a color grading texture serialized by Babylon.
  38206. * @param parsedTexture The texture information being parsedTexture
  38207. * @param scene The scene to load the texture in
  38208. * @param rootUrl The root url of the data assets to load
  38209. * @return A color gradind texture
  38210. */
  38211. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38212. var texture = null;
  38213. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38214. texture = new ColorGradingTexture(parsedTexture.name, scene);
  38215. texture.name = parsedTexture.name;
  38216. texture.level = parsedTexture.level;
  38217. }
  38218. return texture;
  38219. };
  38220. /**
  38221. * Serializes the LUT texture to json format.
  38222. */
  38223. ColorGradingTexture.prototype.serialize = function () {
  38224. if (!this.name) {
  38225. return null;
  38226. }
  38227. var serializationObject = {};
  38228. serializationObject.name = this.name;
  38229. serializationObject.level = this.level;
  38230. serializationObject.customType = "BABYLON.ColorGradingTexture";
  38231. return serializationObject;
  38232. };
  38233. /**
  38234. * Empty line regex stored for GC.
  38235. */
  38236. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  38237. return ColorGradingTexture;
  38238. }(BABYLON.BaseTexture));
  38239. BABYLON.ColorGradingTexture = ColorGradingTexture;
  38240. })(BABYLON || (BABYLON = {}));
  38241. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  38242. "use strict";
  38243. var BABYLON;
  38244. (function (BABYLON) {
  38245. /**
  38246. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38247. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38248. * 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;
  38249. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38250. */
  38251. var ColorCurves = /** @class */ (function () {
  38252. function ColorCurves() {
  38253. this._dirty = true;
  38254. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  38255. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  38256. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38257. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  38258. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38259. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  38260. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  38261. this._globalHue = 30;
  38262. this._globalDensity = 0;
  38263. this._globalSaturation = 0;
  38264. this._globalExposure = 0;
  38265. this._highlightsHue = 30;
  38266. this._highlightsDensity = 0;
  38267. this._highlightsSaturation = 0;
  38268. this._highlightsExposure = 0;
  38269. this._midtonesHue = 30;
  38270. this._midtonesDensity = 0;
  38271. this._midtonesSaturation = 0;
  38272. this._midtonesExposure = 0;
  38273. this._shadowsHue = 30;
  38274. this._shadowsDensity = 0;
  38275. this._shadowsSaturation = 0;
  38276. this._shadowsExposure = 0;
  38277. }
  38278. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  38279. /**
  38280. * Gets the global Hue value.
  38281. * 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).
  38282. */
  38283. get: function () {
  38284. return this._globalHue;
  38285. },
  38286. /**
  38287. * Sets the global Hue value.
  38288. * 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).
  38289. */
  38290. set: function (value) {
  38291. this._globalHue = value;
  38292. this._dirty = true;
  38293. },
  38294. enumerable: true,
  38295. configurable: true
  38296. });
  38297. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  38298. /**
  38299. * Gets the global Density value.
  38300. * 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.
  38301. * Values less than zero provide a filter of opposite hue.
  38302. */
  38303. get: function () {
  38304. return this._globalDensity;
  38305. },
  38306. /**
  38307. * Sets the global Density value.
  38308. * 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.
  38309. * Values less than zero provide a filter of opposite hue.
  38310. */
  38311. set: function (value) {
  38312. this._globalDensity = value;
  38313. this._dirty = true;
  38314. },
  38315. enumerable: true,
  38316. configurable: true
  38317. });
  38318. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  38319. /**
  38320. * Gets the global Saturation value.
  38321. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  38322. */
  38323. get: function () {
  38324. return this._globalSaturation;
  38325. },
  38326. /**
  38327. * Sets the global Saturation value.
  38328. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  38329. */
  38330. set: function (value) {
  38331. this._globalSaturation = value;
  38332. this._dirty = true;
  38333. },
  38334. enumerable: true,
  38335. configurable: true
  38336. });
  38337. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  38338. /**
  38339. * Gets the highlights Hue value.
  38340. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  38341. */
  38342. get: function () {
  38343. return this._highlightsHue;
  38344. },
  38345. /**
  38346. * Sets the highlights Hue value.
  38347. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  38348. */
  38349. set: function (value) {
  38350. this._highlightsHue = value;
  38351. this._dirty = true;
  38352. },
  38353. enumerable: true,
  38354. configurable: true
  38355. });
  38356. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38357. /**
  38358. * Gets the highlights Density value.
  38359. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  38360. * Values less than zero provide a filter of opposite hue.
  38361. */
  38362. get: function () {
  38363. return this._highlightsDensity;
  38364. },
  38365. /**
  38366. * Sets the highlights Density value.
  38367. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  38368. * Values less than zero provide a filter of opposite hue.
  38369. */
  38370. set: function (value) {
  38371. this._highlightsDensity = value;
  38372. this._dirty = true;
  38373. },
  38374. enumerable: true,
  38375. configurable: true
  38376. });
  38377. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38378. /**
  38379. * Gets the highlights Saturation value.
  38380. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  38381. */
  38382. get: function () {
  38383. return this._highlightsSaturation;
  38384. },
  38385. /**
  38386. * Sets the highlights Saturation value.
  38387. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  38388. */
  38389. set: function (value) {
  38390. this._highlightsSaturation = value;
  38391. this._dirty = true;
  38392. },
  38393. enumerable: true,
  38394. configurable: true
  38395. });
  38396. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38397. /**
  38398. * Gets the highlights Exposure value.
  38399. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  38400. */
  38401. get: function () {
  38402. return this._highlightsExposure;
  38403. },
  38404. /**
  38405. * Sets the highlights Exposure value.
  38406. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  38407. */
  38408. set: function (value) {
  38409. this._highlightsExposure = value;
  38410. this._dirty = true;
  38411. },
  38412. enumerable: true,
  38413. configurable: true
  38414. });
  38415. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38416. /**
  38417. * Gets the midtones Hue value.
  38418. * 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).
  38419. */
  38420. get: function () {
  38421. return this._midtonesHue;
  38422. },
  38423. /**
  38424. * Sets the midtones Hue value.
  38425. * 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).
  38426. */
  38427. set: function (value) {
  38428. this._midtonesHue = value;
  38429. this._dirty = true;
  38430. },
  38431. enumerable: true,
  38432. configurable: true
  38433. });
  38434. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38435. /**
  38436. * Gets the midtones Density value.
  38437. * 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.
  38438. * Values less than zero provide a filter of opposite hue.
  38439. */
  38440. get: function () {
  38441. return this._midtonesDensity;
  38442. },
  38443. /**
  38444. * Sets the midtones Density value.
  38445. * 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.
  38446. * Values less than zero provide a filter of opposite hue.
  38447. */
  38448. set: function (value) {
  38449. this._midtonesDensity = value;
  38450. this._dirty = true;
  38451. },
  38452. enumerable: true,
  38453. configurable: true
  38454. });
  38455. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38456. /**
  38457. * Gets the midtones Saturation value.
  38458. * 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.
  38459. */
  38460. get: function () {
  38461. return this._midtonesSaturation;
  38462. },
  38463. /**
  38464. * Sets the midtones Saturation value.
  38465. * 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.
  38466. */
  38467. set: function (value) {
  38468. this._midtonesSaturation = value;
  38469. this._dirty = true;
  38470. },
  38471. enumerable: true,
  38472. configurable: true
  38473. });
  38474. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38475. /**
  38476. * Gets the midtones Exposure value.
  38477. * 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.
  38478. */
  38479. get: function () {
  38480. return this._midtonesExposure;
  38481. },
  38482. /**
  38483. * Sets the midtones Exposure value.
  38484. * 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.
  38485. */
  38486. set: function (value) {
  38487. this._midtonesExposure = value;
  38488. this._dirty = true;
  38489. },
  38490. enumerable: true,
  38491. configurable: true
  38492. });
  38493. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38494. /**
  38495. * Gets the shadows Hue value.
  38496. * 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).
  38497. */
  38498. get: function () {
  38499. return this._shadowsHue;
  38500. },
  38501. /**
  38502. * Sets the shadows Hue value.
  38503. * 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).
  38504. */
  38505. set: function (value) {
  38506. this._shadowsHue = value;
  38507. this._dirty = true;
  38508. },
  38509. enumerable: true,
  38510. configurable: true
  38511. });
  38512. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38513. /**
  38514. * Gets the shadows Density value.
  38515. * 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.
  38516. * Values less than zero provide a filter of opposite hue.
  38517. */
  38518. get: function () {
  38519. return this._shadowsDensity;
  38520. },
  38521. /**
  38522. * Sets the shadows Density value.
  38523. * 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.
  38524. * Values less than zero provide a filter of opposite hue.
  38525. */
  38526. set: function (value) {
  38527. this._shadowsDensity = value;
  38528. this._dirty = true;
  38529. },
  38530. enumerable: true,
  38531. configurable: true
  38532. });
  38533. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38534. /**
  38535. * Gets the shadows Saturation value.
  38536. * 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.
  38537. */
  38538. get: function () {
  38539. return this._shadowsSaturation;
  38540. },
  38541. /**
  38542. * Sets the shadows Saturation value.
  38543. * 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.
  38544. */
  38545. set: function (value) {
  38546. this._shadowsSaturation = value;
  38547. this._dirty = true;
  38548. },
  38549. enumerable: true,
  38550. configurable: true
  38551. });
  38552. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38553. /**
  38554. * Gets the shadows Exposure value.
  38555. * 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.
  38556. */
  38557. get: function () {
  38558. return this._shadowsExposure;
  38559. },
  38560. /**
  38561. * Sets the shadows Exposure value.
  38562. * 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.
  38563. */
  38564. set: function (value) {
  38565. this._shadowsExposure = value;
  38566. this._dirty = true;
  38567. },
  38568. enumerable: true,
  38569. configurable: true
  38570. });
  38571. ColorCurves.prototype.getClassName = function () {
  38572. return "ColorCurves";
  38573. };
  38574. /**
  38575. * Binds the color curves to the shader.
  38576. * @param colorCurves The color curve to bind
  38577. * @param effect The effect to bind to
  38578. */
  38579. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38580. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38581. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38582. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38583. if (colorCurves._dirty) {
  38584. colorCurves._dirty = false;
  38585. // Fill in global info.
  38586. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38587. // Compute highlights info.
  38588. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38589. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38590. // Compute midtones info.
  38591. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38592. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38593. // Compute shadows info.
  38594. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38595. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38596. // Compute deltas (neutral is midtones).
  38597. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38598. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38599. }
  38600. if (effect) {
  38601. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38602. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38603. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38604. }
  38605. };
  38606. /**
  38607. * Prepare the list of uniforms associated with the ColorCurves effects.
  38608. * @param uniformsList The list of uniforms used in the effect
  38609. */
  38610. ColorCurves.PrepareUniforms = function (uniformsList) {
  38611. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38612. };
  38613. /**
  38614. * Returns color grading data based on a hue, density, saturation and exposure value.
  38615. * @param filterHue The hue of the color filter.
  38616. * @param filterDensity The density of the color filter.
  38617. * @param saturation The saturation.
  38618. * @param exposure The exposure.
  38619. * @param result The result data container.
  38620. */
  38621. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38622. if (hue == null) {
  38623. return;
  38624. }
  38625. hue = ColorCurves.clamp(hue, 0, 360);
  38626. density = ColorCurves.clamp(density, -100, 100);
  38627. saturation = ColorCurves.clamp(saturation, -100, 100);
  38628. exposure = ColorCurves.clamp(exposure, -100, 100);
  38629. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38630. // so that the maximum filter density is only 50% control. This provides fine control
  38631. // for small values and reasonable range.
  38632. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38633. density *= 0.5;
  38634. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38635. if (density < 0) {
  38636. density *= -1;
  38637. hue = (hue + 180) % 360;
  38638. }
  38639. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38640. result.scaleToRef(2, result);
  38641. result.a = 1 + 0.01 * saturation;
  38642. };
  38643. /**
  38644. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38645. * @param value The input slider value in range [-100,100].
  38646. * @returns Adjusted value.
  38647. */
  38648. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38649. value /= 100;
  38650. var x = Math.abs(value);
  38651. x = Math.pow(x, 2);
  38652. if (value < 0) {
  38653. x *= -1;
  38654. }
  38655. x *= 100;
  38656. return x;
  38657. };
  38658. /**
  38659. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38660. * @param hue The hue (H) input.
  38661. * @param saturation The saturation (S) input.
  38662. * @param brightness The brightness (B) input.
  38663. * @result An RGBA color represented as Vector4.
  38664. */
  38665. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38666. var h = ColorCurves.clamp(hue, 0, 360);
  38667. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38668. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38669. if (s === 0) {
  38670. result.r = v;
  38671. result.g = v;
  38672. result.b = v;
  38673. }
  38674. else {
  38675. // sector 0 to 5
  38676. h /= 60;
  38677. var i = Math.floor(h);
  38678. // fractional part of h
  38679. var f = h - i;
  38680. var p = v * (1 - s);
  38681. var q = v * (1 - s * f);
  38682. var t = v * (1 - s * (1 - f));
  38683. switch (i) {
  38684. case 0:
  38685. result.r = v;
  38686. result.g = t;
  38687. result.b = p;
  38688. break;
  38689. case 1:
  38690. result.r = q;
  38691. result.g = v;
  38692. result.b = p;
  38693. break;
  38694. case 2:
  38695. result.r = p;
  38696. result.g = v;
  38697. result.b = t;
  38698. break;
  38699. case 3:
  38700. result.r = p;
  38701. result.g = q;
  38702. result.b = v;
  38703. break;
  38704. case 4:
  38705. result.r = t;
  38706. result.g = p;
  38707. result.b = v;
  38708. break;
  38709. default:// case 5:
  38710. result.r = v;
  38711. result.g = p;
  38712. result.b = q;
  38713. break;
  38714. }
  38715. }
  38716. result.a = 1;
  38717. };
  38718. /**
  38719. * Returns a value clamped between min and max
  38720. * @param value The value to clamp
  38721. * @param min The minimum of value
  38722. * @param max The maximum of value
  38723. * @returns The clamped value.
  38724. */
  38725. ColorCurves.clamp = function (value, min, max) {
  38726. return Math.min(Math.max(value, min), max);
  38727. };
  38728. /**
  38729. * Clones the current color curve instance.
  38730. * @return The cloned curves
  38731. */
  38732. ColorCurves.prototype.clone = function () {
  38733. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38734. };
  38735. /**
  38736. * Serializes the current color curve instance to a json representation.
  38737. * @return a JSON representation
  38738. */
  38739. ColorCurves.prototype.serialize = function () {
  38740. return BABYLON.SerializationHelper.Serialize(this);
  38741. };
  38742. /**
  38743. * Parses the color curve from a json representation.
  38744. * @param source the JSON source to parse
  38745. * @return The parsed curves
  38746. */
  38747. ColorCurves.Parse = function (source) {
  38748. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38749. };
  38750. __decorate([
  38751. BABYLON.serialize()
  38752. ], ColorCurves.prototype, "_globalHue", void 0);
  38753. __decorate([
  38754. BABYLON.serialize()
  38755. ], ColorCurves.prototype, "_globalDensity", void 0);
  38756. __decorate([
  38757. BABYLON.serialize()
  38758. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38759. __decorate([
  38760. BABYLON.serialize()
  38761. ], ColorCurves.prototype, "_globalExposure", void 0);
  38762. __decorate([
  38763. BABYLON.serialize()
  38764. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38765. __decorate([
  38766. BABYLON.serialize()
  38767. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38768. __decorate([
  38769. BABYLON.serialize()
  38770. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38771. __decorate([
  38772. BABYLON.serialize()
  38773. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38774. __decorate([
  38775. BABYLON.serialize()
  38776. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38777. __decorate([
  38778. BABYLON.serialize()
  38779. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38780. __decorate([
  38781. BABYLON.serialize()
  38782. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38783. __decorate([
  38784. BABYLON.serialize()
  38785. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38786. return ColorCurves;
  38787. }());
  38788. BABYLON.ColorCurves = ColorCurves;
  38789. })(BABYLON || (BABYLON = {}));
  38790. //# sourceMappingURL=babylon.colorCurves.js.map
  38791. "use strict";
  38792. //# sourceMappingURL=babylon.behavior.js.map
  38793. "use strict";
  38794. var BABYLON;
  38795. (function (BABYLON) {
  38796. /**
  38797. * "Static Class" containing the most commonly used helper while dealing with material for
  38798. * rendering purpose.
  38799. *
  38800. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38801. *
  38802. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38803. */
  38804. var MaterialHelper = /** @class */ (function () {
  38805. function MaterialHelper() {
  38806. }
  38807. /**
  38808. * Bind the current view position to an effect.
  38809. * @param effect The effect to be bound
  38810. * @param scene The scene the eyes position is used from
  38811. */
  38812. MaterialHelper.BindEyePosition = function (effect, scene) {
  38813. if (scene._forcedViewPosition) {
  38814. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38815. return;
  38816. }
  38817. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38818. };
  38819. /**
  38820. * Helps preparing the defines values about the UVs in used in the effect.
  38821. * UVs are shared as much as we can accross chanels in the shaders.
  38822. * @param texture The texture we are preparing the UVs for
  38823. * @param defines The defines to update
  38824. * @param key The chanel key "diffuse", "specular"... used in the shader
  38825. */
  38826. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38827. defines._needUVs = true;
  38828. defines[key] = true;
  38829. if (texture.getTextureMatrix().isIdentity(true)) {
  38830. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38831. if (texture.coordinatesIndex === 0) {
  38832. defines["MAINUV1"] = true;
  38833. }
  38834. else {
  38835. defines["MAINUV2"] = true;
  38836. }
  38837. }
  38838. else {
  38839. defines[key + "DIRECTUV"] = 0;
  38840. }
  38841. };
  38842. /**
  38843. * Binds a texture matrix value to its corrsponding uniform
  38844. * @param texture The texture to bind the matrix for
  38845. * @param uniformBuffer The uniform buffer receivin the data
  38846. * @param key The chanel key "diffuse", "specular"... used in the shader
  38847. */
  38848. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38849. var matrix = texture.getTextureMatrix();
  38850. if (!matrix.isIdentity(true)) {
  38851. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38852. }
  38853. };
  38854. /**
  38855. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38856. * @param mesh defines the current mesh
  38857. * @param scene defines the current scene
  38858. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38859. * @param pointsCloud defines if point cloud rendering has to be turned on
  38860. * @param fogEnabled defines if fog has to be turned on
  38861. * @param alphaTest defines if alpha testing has to be turned on
  38862. * @param defines defines the current list of defines
  38863. */
  38864. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38865. if (defines._areMiscDirty) {
  38866. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38867. defines["POINTSIZE"] = pointsCloud;
  38868. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38869. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38870. defines["ALPHATEST"] = alphaTest;
  38871. }
  38872. };
  38873. /**
  38874. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38875. * @param scene defines the current scene
  38876. * @param engine defines the current engine
  38877. * @param defines specifies the list of active defines
  38878. * @param useInstances defines if instances have to be turned on
  38879. * @param useClipPlane defines if clip plane have to be turned on
  38880. */
  38881. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38882. if (useClipPlane === void 0) { useClipPlane = null; }
  38883. var changed = false;
  38884. if (useClipPlane == null) {
  38885. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38886. }
  38887. if (defines["CLIPPLANE"] !== useClipPlane) {
  38888. defines["CLIPPLANE"] = useClipPlane;
  38889. changed = true;
  38890. }
  38891. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38892. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38893. changed = true;
  38894. }
  38895. if (defines["INSTANCES"] !== useInstances) {
  38896. defines["INSTANCES"] = useInstances;
  38897. changed = true;
  38898. }
  38899. if (changed) {
  38900. defines.markAsUnprocessed();
  38901. }
  38902. };
  38903. /**
  38904. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38905. * @param mesh The mesh containing the geometry data we will draw
  38906. * @param defines The defines to update
  38907. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38908. * @param useBones Precise whether bones should be used or not (override mesh info)
  38909. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38910. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38911. * @returns false if defines are considered not dirty and have not been checked
  38912. */
  38913. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38914. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38915. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38916. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38917. return false;
  38918. }
  38919. defines._normals = defines._needNormals;
  38920. defines._uvs = defines._needUVs;
  38921. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38922. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38923. defines["TANGENT"] = true;
  38924. }
  38925. if (defines._needUVs) {
  38926. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38927. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38928. }
  38929. else {
  38930. defines["UV1"] = false;
  38931. defines["UV2"] = false;
  38932. }
  38933. if (useVertexColor) {
  38934. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38935. defines["VERTEXCOLOR"] = hasVertexColors;
  38936. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38937. }
  38938. if (useBones) {
  38939. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38940. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38941. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38942. }
  38943. else {
  38944. defines["NUM_BONE_INFLUENCERS"] = 0;
  38945. defines["BonesPerMesh"] = 0;
  38946. }
  38947. }
  38948. if (useMorphTargets) {
  38949. var manager = mesh.morphTargetManager;
  38950. if (manager) {
  38951. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38952. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38953. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38954. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38955. }
  38956. else {
  38957. defines["MORPHTARGETS_TANGENT"] = false;
  38958. defines["MORPHTARGETS_NORMAL"] = false;
  38959. defines["MORPHTARGETS"] = false;
  38960. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38961. }
  38962. }
  38963. return true;
  38964. };
  38965. /**
  38966. * Prepares the defines related to the light information passed in parameter
  38967. * @param scene The scene we are intending to draw
  38968. * @param mesh The mesh the effect is compiling for
  38969. * @param defines The defines to update
  38970. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38971. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38972. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38973. * @returns true if normals will be required for the rest of the effect
  38974. */
  38975. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38976. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38977. if (disableLighting === void 0) { disableLighting = false; }
  38978. if (!defines._areLightsDirty) {
  38979. return defines._needNormals;
  38980. }
  38981. var lightIndex = 0;
  38982. var needNormals = false;
  38983. var needRebuild = false;
  38984. var lightmapMode = false;
  38985. var shadowEnabled = false;
  38986. var specularEnabled = false;
  38987. if (scene.lightsEnabled && !disableLighting) {
  38988. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38989. var light = _a[_i];
  38990. needNormals = true;
  38991. if (defines["LIGHT" + lightIndex] === undefined) {
  38992. needRebuild = true;
  38993. }
  38994. defines["LIGHT" + lightIndex] = true;
  38995. defines["SPOTLIGHT" + lightIndex] = false;
  38996. defines["HEMILIGHT" + lightIndex] = false;
  38997. defines["POINTLIGHT" + lightIndex] = false;
  38998. defines["DIRLIGHT" + lightIndex] = false;
  38999. var type;
  39000. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  39001. type = "SPOTLIGHT" + lightIndex;
  39002. var spotLight = light;
  39003. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  39004. }
  39005. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  39006. type = "HEMILIGHT" + lightIndex;
  39007. }
  39008. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  39009. type = "POINTLIGHT" + lightIndex;
  39010. }
  39011. else {
  39012. type = "DIRLIGHT" + lightIndex;
  39013. }
  39014. defines[type] = true;
  39015. // Specular
  39016. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  39017. specularEnabled = true;
  39018. }
  39019. // Shadows
  39020. defines["SHADOW" + lightIndex] = false;
  39021. defines["SHADOWPCF" + lightIndex] = false;
  39022. defines["SHADOWPCSS" + lightIndex] = false;
  39023. defines["SHADOWPOISSON" + lightIndex] = false;
  39024. defines["SHADOWESM" + lightIndex] = false;
  39025. defines["SHADOWCUBE" + lightIndex] = false;
  39026. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  39027. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  39028. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  39029. var shadowGenerator = light.getShadowGenerator();
  39030. if (shadowGenerator) {
  39031. shadowEnabled = true;
  39032. shadowGenerator.prepareDefines(defines, lightIndex);
  39033. }
  39034. }
  39035. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  39036. lightmapMode = true;
  39037. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  39038. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  39039. }
  39040. else {
  39041. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  39042. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  39043. }
  39044. lightIndex++;
  39045. if (lightIndex === maxSimultaneousLights)
  39046. break;
  39047. }
  39048. }
  39049. defines["SPECULARTERM"] = specularEnabled;
  39050. defines["SHADOWS"] = shadowEnabled;
  39051. // Resetting all other lights if any
  39052. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  39053. if (defines["LIGHT" + index] !== undefined) {
  39054. defines["LIGHT" + index] = false;
  39055. defines["HEMILIGHT" + lightIndex] = false;
  39056. defines["POINTLIGHT" + lightIndex] = false;
  39057. defines["DIRLIGHT" + lightIndex] = false;
  39058. defines["SPOTLIGHT" + lightIndex] = false;
  39059. defines["SHADOW" + lightIndex] = false;
  39060. }
  39061. }
  39062. var caps = scene.getEngine().getCaps();
  39063. if (defines["SHADOWFLOAT"] === undefined) {
  39064. needRebuild = true;
  39065. }
  39066. defines["SHADOWFLOAT"] = shadowEnabled &&
  39067. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  39068. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  39069. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  39070. if (needRebuild) {
  39071. defines.rebuild();
  39072. }
  39073. return needNormals;
  39074. };
  39075. /**
  39076. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  39077. * that won t be acctive due to defines being turned off.
  39078. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  39079. * @param samplersList The samplers list
  39080. * @param defines The defines helping in the list generation
  39081. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  39082. */
  39083. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  39084. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39085. var uniformsList;
  39086. var uniformBuffersList = null;
  39087. if (uniformsListOrOptions.uniformsNames) {
  39088. var options = uniformsListOrOptions;
  39089. uniformsList = options.uniformsNames;
  39090. uniformBuffersList = options.uniformBuffersNames;
  39091. samplersList = options.samplers;
  39092. defines = options.defines;
  39093. maxSimultaneousLights = options.maxSimultaneousLights;
  39094. }
  39095. else {
  39096. uniformsList = uniformsListOrOptions;
  39097. if (!samplersList) {
  39098. samplersList = [];
  39099. }
  39100. }
  39101. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39102. if (!defines["LIGHT" + lightIndex]) {
  39103. break;
  39104. }
  39105. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  39106. if (uniformBuffersList) {
  39107. uniformBuffersList.push("Light" + lightIndex);
  39108. }
  39109. samplersList.push("shadowSampler" + lightIndex);
  39110. samplersList.push("depthSampler" + lightIndex);
  39111. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  39112. samplersList.push("projectionLightSampler" + lightIndex);
  39113. uniformsList.push("textureProjectionMatrix" + lightIndex);
  39114. }
  39115. }
  39116. if (defines["NUM_MORPH_INFLUENCERS"]) {
  39117. uniformsList.push("morphTargetInfluences");
  39118. }
  39119. };
  39120. /**
  39121. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  39122. * @param defines The defines to update while falling back
  39123. * @param fallbacks The authorized effect fallbacks
  39124. * @param maxSimultaneousLights The maximum number of lights allowed
  39125. * @param rank the current rank of the Effect
  39126. * @returns The newly affected rank
  39127. */
  39128. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  39129. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39130. if (rank === void 0) { rank = 0; }
  39131. var lightFallbackRank = 0;
  39132. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39133. if (!defines["LIGHT" + lightIndex]) {
  39134. break;
  39135. }
  39136. if (lightIndex > 0) {
  39137. lightFallbackRank = rank + lightIndex;
  39138. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  39139. }
  39140. if (!defines["SHADOWS"]) {
  39141. if (defines["SHADOW" + lightIndex]) {
  39142. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  39143. }
  39144. if (defines["SHADOWPCF" + lightIndex]) {
  39145. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  39146. }
  39147. if (defines["SHADOWPCSS" + lightIndex]) {
  39148. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  39149. }
  39150. if (defines["SHADOWPOISSON" + lightIndex]) {
  39151. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  39152. }
  39153. if (defines["SHADOWESM" + lightIndex]) {
  39154. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  39155. }
  39156. }
  39157. }
  39158. return lightFallbackRank++;
  39159. };
  39160. /**
  39161. * Prepares the list of attributes required for morph targets according to the effect defines.
  39162. * @param attribs The current list of supported attribs
  39163. * @param mesh The mesh to prepare the morph targets attributes for
  39164. * @param defines The current Defines of the effect
  39165. */
  39166. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  39167. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  39168. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  39169. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  39170. var manager = mesh.morphTargetManager;
  39171. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  39172. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  39173. for (var index = 0; index < influencers; index++) {
  39174. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  39175. if (normal) {
  39176. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  39177. }
  39178. if (tangent) {
  39179. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  39180. }
  39181. if (attribs.length > maxAttributesCount) {
  39182. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  39183. }
  39184. }
  39185. }
  39186. };
  39187. /**
  39188. * Prepares the list of attributes required for bones according to the effect defines.
  39189. * @param attribs The current list of supported attribs
  39190. * @param mesh The mesh to prepare the bones attributes for
  39191. * @param defines The current Defines of the effect
  39192. * @param fallbacks The current efffect fallback strategy
  39193. */
  39194. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  39195. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  39196. fallbacks.addCPUSkinningFallback(0, mesh);
  39197. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39198. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39199. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  39200. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39201. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39202. }
  39203. }
  39204. };
  39205. /**
  39206. * Prepares the list of attributes required for instances according to the effect defines.
  39207. * @param attribs The current list of supported attribs
  39208. * @param defines The current Defines of the effect
  39209. */
  39210. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  39211. if (defines["INSTANCES"]) {
  39212. attribs.push("world0");
  39213. attribs.push("world1");
  39214. attribs.push("world2");
  39215. attribs.push("world3");
  39216. }
  39217. };
  39218. /**
  39219. * Binds the light shadow information to the effect for the given mesh.
  39220. * @param light The light containing the generator
  39221. * @param scene The scene the lights belongs to
  39222. * @param mesh The mesh we are binding the information to render
  39223. * @param lightIndex The light index in the effect used to render the mesh
  39224. * @param effect The effect we are binding the data to
  39225. */
  39226. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  39227. if (light.shadowEnabled && mesh.receiveShadows) {
  39228. var shadowGenerator = light.getShadowGenerator();
  39229. if (shadowGenerator) {
  39230. shadowGenerator.bindShadowLight(lightIndex, effect);
  39231. }
  39232. }
  39233. };
  39234. /**
  39235. * Binds the light information to the effect.
  39236. * @param light The light containing the generator
  39237. * @param effect The effect we are binding the data to
  39238. * @param lightIndex The light index in the effect used to render
  39239. */
  39240. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  39241. light.transferToEffect(effect, lightIndex + "");
  39242. };
  39243. /**
  39244. * Binds the lights information from the scene to the effect for the given mesh.
  39245. * @param scene The scene the lights belongs to
  39246. * @param mesh The mesh we are binding the information to render
  39247. * @param effect The effect we are binding the data to
  39248. * @param defines The generated defines for the effect
  39249. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  39250. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  39251. */
  39252. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  39253. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39254. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  39255. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  39256. for (var i = 0; i < len; i++) {
  39257. var light = mesh._lightSources[i];
  39258. var iAsString = i.toString();
  39259. var scaledIntensity = light.getScaledIntensity();
  39260. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  39261. MaterialHelper.BindLightProperties(light, effect, i);
  39262. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  39263. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  39264. if (defines["SPECULARTERM"]) {
  39265. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  39266. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  39267. }
  39268. // Shadows
  39269. if (scene.shadowsEnabled) {
  39270. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  39271. }
  39272. light._uniformBuffer.update();
  39273. }
  39274. };
  39275. /**
  39276. * Binds the fog information from the scene to the effect for the given mesh.
  39277. * @param scene The scene the lights belongs to
  39278. * @param mesh The mesh we are binding the information to render
  39279. * @param effect The effect we are binding the data to
  39280. */
  39281. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  39282. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  39283. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  39284. effect.setColor3("vFogColor", scene.fogColor);
  39285. }
  39286. };
  39287. /**
  39288. * Binds the bones information from the mesh to the effect.
  39289. * @param mesh The mesh we are binding the information to render
  39290. * @param effect The effect we are binding the data to
  39291. */
  39292. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  39293. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39294. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  39295. if (matrices && effect) {
  39296. effect.setMatrices("mBones", matrices);
  39297. }
  39298. }
  39299. };
  39300. /**
  39301. * Binds the morph targets information from the mesh to the effect.
  39302. * @param abstractMesh The mesh we are binding the information to render
  39303. * @param effect The effect we are binding the data to
  39304. */
  39305. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  39306. var manager = abstractMesh.morphTargetManager;
  39307. if (!abstractMesh || !manager) {
  39308. return;
  39309. }
  39310. effect.setFloatArray("morphTargetInfluences", manager.influences);
  39311. };
  39312. /**
  39313. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  39314. * @param defines The generated defines used in the effect
  39315. * @param effect The effect we are binding the data to
  39316. * @param scene The scene we are willing to render with logarithmic scale for
  39317. */
  39318. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  39319. if (defines["LOGARITHMICDEPTH"]) {
  39320. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  39321. }
  39322. };
  39323. /**
  39324. * Binds the clip plane information from the scene to the effect.
  39325. * @param scene The scene the clip plane information are extracted from
  39326. * @param effect The effect we are binding the data to
  39327. */
  39328. MaterialHelper.BindClipPlane = function (effect, scene) {
  39329. if (scene.clipPlane) {
  39330. var clipPlane = scene.clipPlane;
  39331. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  39332. }
  39333. };
  39334. return MaterialHelper;
  39335. }());
  39336. BABYLON.MaterialHelper = MaterialHelper;
  39337. })(BABYLON || (BABYLON = {}));
  39338. //# sourceMappingURL=babylon.materialHelper.js.map
  39339. "use strict";
  39340. var BABYLON;
  39341. (function (BABYLON) {
  39342. var PushMaterial = /** @class */ (function (_super) {
  39343. __extends(PushMaterial, _super);
  39344. function PushMaterial(name, scene) {
  39345. var _this = _super.call(this, name, scene) || this;
  39346. _this._normalMatrix = new BABYLON.Matrix();
  39347. _this.storeEffectOnSubMeshes = true;
  39348. return _this;
  39349. }
  39350. PushMaterial.prototype.getEffect = function () {
  39351. return this._activeEffect;
  39352. };
  39353. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  39354. if (!mesh) {
  39355. return false;
  39356. }
  39357. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  39358. return true;
  39359. }
  39360. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  39361. };
  39362. /**
  39363. * Binds the given world matrix to the active effect
  39364. *
  39365. * @param world the matrix to bind
  39366. */
  39367. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39368. this._activeEffect.setMatrix("world", world);
  39369. };
  39370. /**
  39371. * Binds the given normal matrix to the active effect
  39372. *
  39373. * @param normalMatrix the matrix to bind
  39374. */
  39375. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  39376. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  39377. };
  39378. PushMaterial.prototype.bind = function (world, mesh) {
  39379. if (!mesh) {
  39380. return;
  39381. }
  39382. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  39383. };
  39384. PushMaterial.prototype._afterBind = function (mesh, effect) {
  39385. if (effect === void 0) { effect = null; }
  39386. _super.prototype._afterBind.call(this, mesh);
  39387. this.getScene()._cachedEffect = effect;
  39388. };
  39389. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  39390. if (visibility === void 0) { visibility = 1; }
  39391. return scene.isCachedMaterialInvalid(this, effect, visibility);
  39392. };
  39393. return PushMaterial;
  39394. }(BABYLON.Material));
  39395. BABYLON.PushMaterial = PushMaterial;
  39396. })(BABYLON || (BABYLON = {}));
  39397. //# sourceMappingURL=babylon.pushMaterial.js.map
  39398. "use strict";
  39399. var BABYLON;
  39400. (function (BABYLON) {
  39401. /** @ignore */
  39402. var StandardMaterialDefines = /** @class */ (function (_super) {
  39403. __extends(StandardMaterialDefines, _super);
  39404. function StandardMaterialDefines() {
  39405. var _this = _super.call(this) || this;
  39406. _this.MAINUV1 = false;
  39407. _this.MAINUV2 = false;
  39408. _this.DIFFUSE = false;
  39409. _this.DIFFUSEDIRECTUV = 0;
  39410. _this.AMBIENT = false;
  39411. _this.AMBIENTDIRECTUV = 0;
  39412. _this.OPACITY = false;
  39413. _this.OPACITYDIRECTUV = 0;
  39414. _this.OPACITYRGB = false;
  39415. _this.REFLECTION = false;
  39416. _this.EMISSIVE = false;
  39417. _this.EMISSIVEDIRECTUV = 0;
  39418. _this.SPECULAR = false;
  39419. _this.SPECULARDIRECTUV = 0;
  39420. _this.BUMP = false;
  39421. _this.BUMPDIRECTUV = 0;
  39422. _this.PARALLAX = false;
  39423. _this.PARALLAXOCCLUSION = false;
  39424. _this.SPECULAROVERALPHA = false;
  39425. _this.CLIPPLANE = false;
  39426. _this.ALPHATEST = false;
  39427. _this.DEPTHPREPASS = false;
  39428. _this.ALPHAFROMDIFFUSE = false;
  39429. _this.POINTSIZE = false;
  39430. _this.FOG = false;
  39431. _this.SPECULARTERM = false;
  39432. _this.DIFFUSEFRESNEL = false;
  39433. _this.OPACITYFRESNEL = false;
  39434. _this.REFLECTIONFRESNEL = false;
  39435. _this.REFRACTIONFRESNEL = false;
  39436. _this.EMISSIVEFRESNEL = false;
  39437. _this.FRESNEL = false;
  39438. _this.NORMAL = false;
  39439. _this.UV1 = false;
  39440. _this.UV2 = false;
  39441. _this.VERTEXCOLOR = false;
  39442. _this.VERTEXALPHA = false;
  39443. _this.NUM_BONE_INFLUENCERS = 0;
  39444. _this.BonesPerMesh = 0;
  39445. _this.INSTANCES = false;
  39446. _this.GLOSSINESS = false;
  39447. _this.ROUGHNESS = false;
  39448. _this.EMISSIVEASILLUMINATION = false;
  39449. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39450. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39451. _this.LIGHTMAP = false;
  39452. _this.LIGHTMAPDIRECTUV = 0;
  39453. _this.OBJECTSPACE_NORMALMAP = false;
  39454. _this.USELIGHTMAPASSHADOWMAP = false;
  39455. _this.REFLECTIONMAP_3D = false;
  39456. _this.REFLECTIONMAP_SPHERICAL = false;
  39457. _this.REFLECTIONMAP_PLANAR = false;
  39458. _this.REFLECTIONMAP_CUBIC = false;
  39459. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39460. _this.REFLECTIONMAP_PROJECTION = false;
  39461. _this.REFLECTIONMAP_SKYBOX = false;
  39462. _this.REFLECTIONMAP_EXPLICIT = false;
  39463. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39464. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39465. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39466. _this.INVERTCUBICMAP = false;
  39467. _this.LOGARITHMICDEPTH = false;
  39468. _this.REFRACTION = false;
  39469. _this.REFRACTIONMAP_3D = false;
  39470. _this.REFLECTIONOVERALPHA = false;
  39471. _this.TWOSIDEDLIGHTING = false;
  39472. _this.SHADOWFLOAT = false;
  39473. _this.MORPHTARGETS = false;
  39474. _this.MORPHTARGETS_NORMAL = false;
  39475. _this.MORPHTARGETS_TANGENT = false;
  39476. _this.NUM_MORPH_INFLUENCERS = 0;
  39477. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39478. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39479. _this.IMAGEPROCESSING = false;
  39480. _this.VIGNETTE = false;
  39481. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39482. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39483. _this.TONEMAPPING = false;
  39484. _this.CONTRAST = false;
  39485. _this.COLORCURVES = false;
  39486. _this.COLORGRADING = false;
  39487. _this.COLORGRADING3D = false;
  39488. _this.SAMPLER3DGREENDEPTH = false;
  39489. _this.SAMPLER3DBGRMAP = false;
  39490. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39491. _this.EXPOSURE = false;
  39492. _this.GRAIN = false;
  39493. _this.rebuild();
  39494. return _this;
  39495. }
  39496. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39497. var modes = [
  39498. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39499. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39500. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39501. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39502. ];
  39503. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39504. var mode = modes_1[_i];
  39505. this[mode] = (mode === modeToEnable);
  39506. }
  39507. };
  39508. return StandardMaterialDefines;
  39509. }(BABYLON.MaterialDefines));
  39510. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39511. var StandardMaterial = /** @class */ (function (_super) {
  39512. __extends(StandardMaterial, _super);
  39513. function StandardMaterial(name, scene) {
  39514. var _this = _super.call(this, name, scene) || this;
  39515. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39516. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39517. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39518. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39519. _this.specularPower = 64;
  39520. _this._useAlphaFromDiffuseTexture = false;
  39521. _this._useEmissiveAsIllumination = false;
  39522. _this._linkEmissiveWithDiffuse = false;
  39523. _this._useSpecularOverAlpha = false;
  39524. _this._useReflectionOverAlpha = false;
  39525. _this._disableLighting = false;
  39526. _this._useObjectSpaceNormalMap = false;
  39527. _this._useParallax = false;
  39528. _this._useParallaxOcclusion = false;
  39529. _this.parallaxScaleBias = 0.05;
  39530. _this._roughness = 0;
  39531. _this.indexOfRefraction = 0.98;
  39532. _this.invertRefractionY = true;
  39533. _this._useLightmapAsShadowmap = false;
  39534. _this._useReflectionFresnelFromSpecular = false;
  39535. _this._useGlossinessFromSpecularMapAlpha = false;
  39536. _this._maxSimultaneousLights = 4;
  39537. /**
  39538. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39539. */
  39540. _this._invertNormalMapX = false;
  39541. /**
  39542. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39543. */
  39544. _this._invertNormalMapY = false;
  39545. /**
  39546. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39547. */
  39548. _this._twoSidedLighting = false;
  39549. _this._renderTargets = new BABYLON.SmartArray(16);
  39550. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39551. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39552. // Setup the default processing configuration to the scene.
  39553. _this._attachImageProcessingConfiguration(null);
  39554. _this.getRenderTargetTextures = function () {
  39555. _this._renderTargets.reset();
  39556. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39557. _this._renderTargets.push(_this._reflectionTexture);
  39558. }
  39559. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39560. _this._renderTargets.push(_this._refractionTexture);
  39561. }
  39562. return _this._renderTargets;
  39563. };
  39564. return _this;
  39565. }
  39566. ;
  39567. ;
  39568. ;
  39569. ;
  39570. ;
  39571. ;
  39572. ;
  39573. ;
  39574. ;
  39575. ;
  39576. ;
  39577. ;
  39578. ;
  39579. ;
  39580. ;
  39581. ;
  39582. ;
  39583. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39584. /**
  39585. * Gets the image processing configuration used either in this material.
  39586. */
  39587. get: function () {
  39588. return this._imageProcessingConfiguration;
  39589. },
  39590. /**
  39591. * Sets the Default image processing configuration used either in the this material.
  39592. *
  39593. * If sets to null, the scene one is in use.
  39594. */
  39595. set: function (value) {
  39596. this._attachImageProcessingConfiguration(value);
  39597. // Ensure the effect will be rebuilt.
  39598. this._markAllSubMeshesAsTexturesDirty();
  39599. },
  39600. enumerable: true,
  39601. configurable: true
  39602. });
  39603. /**
  39604. * Attaches a new image processing configuration to the Standard Material.
  39605. * @param configuration
  39606. */
  39607. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39608. var _this = this;
  39609. if (configuration === this._imageProcessingConfiguration) {
  39610. return;
  39611. }
  39612. // Detaches observer.
  39613. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39614. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39615. }
  39616. // Pick the scene configuration if needed.
  39617. if (!configuration) {
  39618. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39619. }
  39620. else {
  39621. this._imageProcessingConfiguration = configuration;
  39622. }
  39623. // Attaches observer.
  39624. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39625. _this._markAllSubMeshesAsImageProcessingDirty();
  39626. });
  39627. };
  39628. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39629. /**
  39630. * Gets wether the color curves effect is enabled.
  39631. */
  39632. get: function () {
  39633. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39634. },
  39635. /**
  39636. * Sets wether the color curves effect is enabled.
  39637. */
  39638. set: function (value) {
  39639. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39640. },
  39641. enumerable: true,
  39642. configurable: true
  39643. });
  39644. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39645. /**
  39646. * Gets wether the color grading effect is enabled.
  39647. */
  39648. get: function () {
  39649. return this.imageProcessingConfiguration.colorGradingEnabled;
  39650. },
  39651. /**
  39652. * Gets wether the color grading effect is enabled.
  39653. */
  39654. set: function (value) {
  39655. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39656. },
  39657. enumerable: true,
  39658. configurable: true
  39659. });
  39660. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39661. /**
  39662. * Gets wether tonemapping is enabled or not.
  39663. */
  39664. get: function () {
  39665. return this._imageProcessingConfiguration.toneMappingEnabled;
  39666. },
  39667. /**
  39668. * Sets wether tonemapping is enabled or not
  39669. */
  39670. set: function (value) {
  39671. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39672. },
  39673. enumerable: true,
  39674. configurable: true
  39675. });
  39676. ;
  39677. ;
  39678. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39679. /**
  39680. * The camera exposure used on this material.
  39681. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39682. * This corresponds to a photographic exposure.
  39683. */
  39684. get: function () {
  39685. return this._imageProcessingConfiguration.exposure;
  39686. },
  39687. /**
  39688. * The camera exposure used on this material.
  39689. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39690. * This corresponds to a photographic exposure.
  39691. */
  39692. set: function (value) {
  39693. this._imageProcessingConfiguration.exposure = value;
  39694. },
  39695. enumerable: true,
  39696. configurable: true
  39697. });
  39698. ;
  39699. ;
  39700. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39701. /**
  39702. * Gets The camera contrast used on this material.
  39703. */
  39704. get: function () {
  39705. return this._imageProcessingConfiguration.contrast;
  39706. },
  39707. /**
  39708. * Sets The camera contrast used on this material.
  39709. */
  39710. set: function (value) {
  39711. this._imageProcessingConfiguration.contrast = value;
  39712. },
  39713. enumerable: true,
  39714. configurable: true
  39715. });
  39716. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39717. /**
  39718. * Gets the Color Grading 2D Lookup Texture.
  39719. */
  39720. get: function () {
  39721. return this._imageProcessingConfiguration.colorGradingTexture;
  39722. },
  39723. /**
  39724. * Sets the Color Grading 2D Lookup Texture.
  39725. */
  39726. set: function (value) {
  39727. this._imageProcessingConfiguration.colorGradingTexture = value;
  39728. },
  39729. enumerable: true,
  39730. configurable: true
  39731. });
  39732. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39733. /**
  39734. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39735. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39736. * 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;
  39737. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39738. */
  39739. get: function () {
  39740. return this._imageProcessingConfiguration.colorCurves;
  39741. },
  39742. /**
  39743. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39744. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39745. * 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;
  39746. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39747. */
  39748. set: function (value) {
  39749. this._imageProcessingConfiguration.colorCurves = value;
  39750. },
  39751. enumerable: true,
  39752. configurable: true
  39753. });
  39754. StandardMaterial.prototype.getClassName = function () {
  39755. return "StandardMaterial";
  39756. };
  39757. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39758. get: function () {
  39759. return this._useLogarithmicDepth;
  39760. },
  39761. set: function (value) {
  39762. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39763. this._markAllSubMeshesAsMiscDirty();
  39764. },
  39765. enumerable: true,
  39766. configurable: true
  39767. });
  39768. StandardMaterial.prototype.needAlphaBlending = function () {
  39769. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39770. };
  39771. StandardMaterial.prototype.needAlphaTesting = function () {
  39772. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39773. };
  39774. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39775. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39776. };
  39777. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39778. return this._diffuseTexture;
  39779. };
  39780. /**
  39781. * Child classes can use it to update shaders
  39782. */
  39783. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39784. if (useInstances === void 0) { useInstances = false; }
  39785. if (subMesh.effect && this.isFrozen) {
  39786. if (this._wasPreviouslyReady && subMesh.effect) {
  39787. return true;
  39788. }
  39789. }
  39790. if (!subMesh._materialDefines) {
  39791. subMesh._materialDefines = new StandardMaterialDefines();
  39792. }
  39793. var scene = this.getScene();
  39794. var defines = subMesh._materialDefines;
  39795. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39796. if (defines._renderId === scene.getRenderId()) {
  39797. return true;
  39798. }
  39799. }
  39800. var engine = scene.getEngine();
  39801. // Lights
  39802. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39803. // Textures
  39804. if (defines._areTexturesDirty) {
  39805. defines._needUVs = false;
  39806. defines.MAINUV1 = false;
  39807. defines.MAINUV2 = false;
  39808. if (scene.texturesEnabled) {
  39809. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39810. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39811. return false;
  39812. }
  39813. else {
  39814. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39815. }
  39816. }
  39817. else {
  39818. defines.DIFFUSE = false;
  39819. }
  39820. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39821. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39822. return false;
  39823. }
  39824. else {
  39825. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39826. }
  39827. }
  39828. else {
  39829. defines.AMBIENT = false;
  39830. }
  39831. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39832. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39833. return false;
  39834. }
  39835. else {
  39836. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39837. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39838. }
  39839. }
  39840. else {
  39841. defines.OPACITY = false;
  39842. }
  39843. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39844. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39845. return false;
  39846. }
  39847. else {
  39848. defines._needNormals = true;
  39849. defines.REFLECTION = true;
  39850. defines.ROUGHNESS = (this._roughness > 0);
  39851. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39852. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39853. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39854. switch (this._reflectionTexture.coordinatesMode) {
  39855. case BABYLON.Texture.CUBIC_MODE:
  39856. case BABYLON.Texture.INVCUBIC_MODE:
  39857. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39858. break;
  39859. case BABYLON.Texture.EXPLICIT_MODE:
  39860. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39861. break;
  39862. case BABYLON.Texture.PLANAR_MODE:
  39863. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39864. break;
  39865. case BABYLON.Texture.PROJECTION_MODE:
  39866. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39867. break;
  39868. case BABYLON.Texture.SKYBOX_MODE:
  39869. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39870. break;
  39871. case BABYLON.Texture.SPHERICAL_MODE:
  39872. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39873. break;
  39874. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39875. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39876. break;
  39877. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39878. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39879. break;
  39880. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39881. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39882. break;
  39883. }
  39884. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39885. }
  39886. }
  39887. else {
  39888. defines.REFLECTION = false;
  39889. }
  39890. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39891. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39892. return false;
  39893. }
  39894. else {
  39895. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39896. }
  39897. }
  39898. else {
  39899. defines.EMISSIVE = false;
  39900. }
  39901. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39902. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39903. return false;
  39904. }
  39905. else {
  39906. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39907. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39908. }
  39909. }
  39910. else {
  39911. defines.LIGHTMAP = false;
  39912. }
  39913. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39914. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39915. return false;
  39916. }
  39917. else {
  39918. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39919. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39920. }
  39921. }
  39922. else {
  39923. defines.SPECULAR = false;
  39924. }
  39925. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39926. // Bump texure can not be not blocking.
  39927. if (!this._bumpTexture.isReady()) {
  39928. return false;
  39929. }
  39930. else {
  39931. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39932. defines.PARALLAX = this._useParallax;
  39933. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39934. }
  39935. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39936. }
  39937. else {
  39938. defines.BUMP = false;
  39939. }
  39940. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39941. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39942. return false;
  39943. }
  39944. else {
  39945. defines._needUVs = true;
  39946. defines.REFRACTION = true;
  39947. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39948. }
  39949. }
  39950. else {
  39951. defines.REFRACTION = false;
  39952. }
  39953. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39954. }
  39955. else {
  39956. defines.DIFFUSE = false;
  39957. defines.AMBIENT = false;
  39958. defines.OPACITY = false;
  39959. defines.REFLECTION = false;
  39960. defines.EMISSIVE = false;
  39961. defines.LIGHTMAP = false;
  39962. defines.BUMP = false;
  39963. defines.REFRACTION = false;
  39964. }
  39965. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39966. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39967. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39968. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39969. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39970. }
  39971. if (defines._areImageProcessingDirty) {
  39972. if (!this._imageProcessingConfiguration.isReady()) {
  39973. return false;
  39974. }
  39975. this._imageProcessingConfiguration.prepareDefines(defines);
  39976. }
  39977. if (defines._areFresnelDirty) {
  39978. if (StandardMaterial.FresnelEnabled) {
  39979. // Fresnel
  39980. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39981. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39982. this._reflectionFresnelParameters) {
  39983. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39984. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39985. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39986. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39987. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39988. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39989. defines._needNormals = true;
  39990. defines.FRESNEL = true;
  39991. }
  39992. }
  39993. else {
  39994. defines.FRESNEL = false;
  39995. }
  39996. }
  39997. // Misc.
  39998. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39999. // Attribs
  40000. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  40001. // Values that need to be evaluated on every frame
  40002. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  40003. // Get correct effect
  40004. if (defines.isDirty) {
  40005. defines.markAsProcessed();
  40006. scene.resetCachedMaterial();
  40007. // Fallbacks
  40008. var fallbacks = new BABYLON.EffectFallbacks();
  40009. if (defines.REFLECTION) {
  40010. fallbacks.addFallback(0, "REFLECTION");
  40011. }
  40012. if (defines.SPECULAR) {
  40013. fallbacks.addFallback(0, "SPECULAR");
  40014. }
  40015. if (defines.BUMP) {
  40016. fallbacks.addFallback(0, "BUMP");
  40017. }
  40018. if (defines.PARALLAX) {
  40019. fallbacks.addFallback(1, "PARALLAX");
  40020. }
  40021. if (defines.PARALLAXOCCLUSION) {
  40022. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  40023. }
  40024. if (defines.SPECULAROVERALPHA) {
  40025. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  40026. }
  40027. if (defines.FOG) {
  40028. fallbacks.addFallback(1, "FOG");
  40029. }
  40030. if (defines.POINTSIZE) {
  40031. fallbacks.addFallback(0, "POINTSIZE");
  40032. }
  40033. if (defines.LOGARITHMICDEPTH) {
  40034. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  40035. }
  40036. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  40037. if (defines.SPECULARTERM) {
  40038. fallbacks.addFallback(0, "SPECULARTERM");
  40039. }
  40040. if (defines.DIFFUSEFRESNEL) {
  40041. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  40042. }
  40043. if (defines.OPACITYFRESNEL) {
  40044. fallbacks.addFallback(2, "OPACITYFRESNEL");
  40045. }
  40046. if (defines.REFLECTIONFRESNEL) {
  40047. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  40048. }
  40049. if (defines.EMISSIVEFRESNEL) {
  40050. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  40051. }
  40052. if (defines.FRESNEL) {
  40053. fallbacks.addFallback(4, "FRESNEL");
  40054. }
  40055. //Attributes
  40056. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40057. if (defines.NORMAL) {
  40058. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40059. }
  40060. if (defines.UV1) {
  40061. attribs.push(BABYLON.VertexBuffer.UVKind);
  40062. }
  40063. if (defines.UV2) {
  40064. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40065. }
  40066. if (defines.VERTEXCOLOR) {
  40067. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40068. }
  40069. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40070. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40071. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40072. var shaderName = "default";
  40073. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  40074. "vFogInfos", "vFogColor", "pointSize",
  40075. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40076. "mBones",
  40077. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  40078. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  40079. "vReflectionPosition", "vReflectionSize",
  40080. "logarithmicDepthConstant", "vTangentSpaceParams"
  40081. ];
  40082. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  40083. var uniformBuffers = ["Material", "Scene"];
  40084. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40085. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40086. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40087. uniformsNames: uniforms,
  40088. uniformBuffersNames: uniformBuffers,
  40089. samplers: samplers,
  40090. defines: defines,
  40091. maxSimultaneousLights: this._maxSimultaneousLights
  40092. });
  40093. if (this.customShaderNameResolve) {
  40094. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  40095. }
  40096. var join = defines.toString();
  40097. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  40098. attributes: attribs,
  40099. uniformsNames: uniforms,
  40100. uniformBuffersNames: uniformBuffers,
  40101. samplers: samplers,
  40102. defines: join,
  40103. fallbacks: fallbacks,
  40104. onCompiled: this.onCompiled,
  40105. onError: this.onError,
  40106. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40107. }, engine), defines);
  40108. this.buildUniformLayout();
  40109. }
  40110. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40111. return false;
  40112. }
  40113. defines._renderId = scene.getRenderId();
  40114. this._wasPreviouslyReady = true;
  40115. return true;
  40116. };
  40117. StandardMaterial.prototype.buildUniformLayout = function () {
  40118. // Order is important !
  40119. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  40120. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  40121. this._uniformBuffer.addUniform("opacityParts", 4);
  40122. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  40123. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  40124. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  40125. this._uniformBuffer.addUniform("refractionRightColor", 4);
  40126. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  40127. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  40128. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  40129. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  40130. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40131. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40132. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40133. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40134. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40135. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40136. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  40137. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40138. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  40139. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40140. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40141. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40142. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40143. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40144. this._uniformBuffer.addUniform("specularMatrix", 16);
  40145. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40146. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40147. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40148. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40149. this._uniformBuffer.addUniform("vSpecularColor", 4);
  40150. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40151. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  40152. this._uniformBuffer.addUniform("pointSize", 1);
  40153. this._uniformBuffer.create();
  40154. };
  40155. StandardMaterial.prototype.unbind = function () {
  40156. if (this._activeEffect) {
  40157. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40158. this._activeEffect.setTexture("reflection2DSampler", null);
  40159. }
  40160. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40161. this._activeEffect.setTexture("refraction2DSampler", null);
  40162. }
  40163. }
  40164. _super.prototype.unbind.call(this);
  40165. };
  40166. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40167. var scene = this.getScene();
  40168. var defines = subMesh._materialDefines;
  40169. if (!defines) {
  40170. return;
  40171. }
  40172. var effect = subMesh.effect;
  40173. if (!effect) {
  40174. return;
  40175. }
  40176. this._activeEffect = effect;
  40177. // Matrices
  40178. this.bindOnlyWorldMatrix(world);
  40179. // Normal Matrix
  40180. if (defines.OBJECTSPACE_NORMALMAP) {
  40181. world.toNormalMatrix(this._normalMatrix);
  40182. this.bindOnlyNormalMatrix(this._normalMatrix);
  40183. }
  40184. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40185. // Bones
  40186. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  40187. if (mustRebind) {
  40188. this._uniformBuffer.bindToEffect(effect, "Material");
  40189. this.bindViewProjection(effect);
  40190. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40191. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  40192. // Fresnel
  40193. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  40194. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  40195. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  40196. }
  40197. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  40198. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  40199. }
  40200. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  40201. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  40202. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  40203. }
  40204. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  40205. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  40206. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  40207. }
  40208. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  40209. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  40210. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  40211. }
  40212. }
  40213. // Textures
  40214. if (scene.texturesEnabled) {
  40215. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40216. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  40217. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  40218. }
  40219. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40220. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  40221. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40222. }
  40223. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40224. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40225. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40226. }
  40227. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40228. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  40229. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  40230. if (this._reflectionTexture.boundingBoxSize) {
  40231. var cubeTexture = this._reflectionTexture;
  40232. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40233. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40234. }
  40235. }
  40236. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40237. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40238. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40239. }
  40240. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40241. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40242. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40243. }
  40244. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40245. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  40246. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  40247. }
  40248. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40249. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  40250. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40251. if (scene._mirroredCameraPosition) {
  40252. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40253. }
  40254. else {
  40255. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40256. }
  40257. }
  40258. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40259. var depth = 1.0;
  40260. if (!this._refractionTexture.isCube) {
  40261. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  40262. if (this._refractionTexture.depth) {
  40263. depth = this._refractionTexture.depth;
  40264. }
  40265. }
  40266. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  40267. }
  40268. }
  40269. // Point size
  40270. if (this.pointsCloud) {
  40271. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40272. }
  40273. if (defines.SPECULARTERM) {
  40274. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  40275. }
  40276. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  40277. // Diffuse
  40278. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  40279. }
  40280. // Textures
  40281. if (scene.texturesEnabled) {
  40282. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40283. effect.setTexture("diffuseSampler", this._diffuseTexture);
  40284. }
  40285. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40286. effect.setTexture("ambientSampler", this._ambientTexture);
  40287. }
  40288. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40289. effect.setTexture("opacitySampler", this._opacityTexture);
  40290. }
  40291. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40292. if (this._reflectionTexture.isCube) {
  40293. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  40294. }
  40295. else {
  40296. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  40297. }
  40298. }
  40299. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40300. effect.setTexture("emissiveSampler", this._emissiveTexture);
  40301. }
  40302. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40303. effect.setTexture("lightmapSampler", this._lightmapTexture);
  40304. }
  40305. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40306. effect.setTexture("specularSampler", this._specularTexture);
  40307. }
  40308. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40309. effect.setTexture("bumpSampler", this._bumpTexture);
  40310. }
  40311. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40312. var depth = 1.0;
  40313. if (this._refractionTexture.isCube) {
  40314. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  40315. }
  40316. else {
  40317. effect.setTexture("refraction2DSampler", this._refractionTexture);
  40318. }
  40319. }
  40320. }
  40321. // Clip plane
  40322. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  40323. // Colors
  40324. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  40325. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  40326. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40327. }
  40328. if (mustRebind || !this.isFrozen) {
  40329. // Lights
  40330. if (scene.lightsEnabled && !this._disableLighting) {
  40331. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  40332. }
  40333. // View
  40334. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  40335. this.bindView(effect);
  40336. }
  40337. // Fog
  40338. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  40339. // Morph targets
  40340. if (defines.NUM_MORPH_INFLUENCERS) {
  40341. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  40342. }
  40343. // Log. depth
  40344. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  40345. // image processing
  40346. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  40347. this._imageProcessingConfiguration.bind(this._activeEffect);
  40348. }
  40349. }
  40350. this._uniformBuffer.update();
  40351. this._afterBind(mesh, this._activeEffect);
  40352. };
  40353. StandardMaterial.prototype.getAnimatables = function () {
  40354. var results = [];
  40355. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  40356. results.push(this._diffuseTexture);
  40357. }
  40358. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40359. results.push(this._ambientTexture);
  40360. }
  40361. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40362. results.push(this._opacityTexture);
  40363. }
  40364. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40365. results.push(this._reflectionTexture);
  40366. }
  40367. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40368. results.push(this._emissiveTexture);
  40369. }
  40370. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  40371. results.push(this._specularTexture);
  40372. }
  40373. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40374. results.push(this._bumpTexture);
  40375. }
  40376. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40377. results.push(this._lightmapTexture);
  40378. }
  40379. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40380. results.push(this._refractionTexture);
  40381. }
  40382. return results;
  40383. };
  40384. StandardMaterial.prototype.getActiveTextures = function () {
  40385. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40386. if (this._diffuseTexture) {
  40387. activeTextures.push(this._diffuseTexture);
  40388. }
  40389. if (this._ambientTexture) {
  40390. activeTextures.push(this._ambientTexture);
  40391. }
  40392. if (this._opacityTexture) {
  40393. activeTextures.push(this._opacityTexture);
  40394. }
  40395. if (this._reflectionTexture) {
  40396. activeTextures.push(this._reflectionTexture);
  40397. }
  40398. if (this._emissiveTexture) {
  40399. activeTextures.push(this._emissiveTexture);
  40400. }
  40401. if (this._specularTexture) {
  40402. activeTextures.push(this._specularTexture);
  40403. }
  40404. if (this._bumpTexture) {
  40405. activeTextures.push(this._bumpTexture);
  40406. }
  40407. if (this._lightmapTexture) {
  40408. activeTextures.push(this._lightmapTexture);
  40409. }
  40410. if (this._refractionTexture) {
  40411. activeTextures.push(this._refractionTexture);
  40412. }
  40413. return activeTextures;
  40414. };
  40415. StandardMaterial.prototype.hasTexture = function (texture) {
  40416. if (_super.prototype.hasTexture.call(this, texture)) {
  40417. return true;
  40418. }
  40419. if (this._diffuseTexture === texture) {
  40420. return true;
  40421. }
  40422. if (this._ambientTexture === texture) {
  40423. return true;
  40424. }
  40425. if (this._opacityTexture === texture) {
  40426. return true;
  40427. }
  40428. if (this._reflectionTexture === texture) {
  40429. return true;
  40430. }
  40431. if (this._emissiveTexture === texture) {
  40432. return true;
  40433. }
  40434. if (this._specularTexture === texture) {
  40435. return true;
  40436. }
  40437. if (this._bumpTexture === texture) {
  40438. return true;
  40439. }
  40440. if (this._lightmapTexture === texture) {
  40441. return true;
  40442. }
  40443. if (this._refractionTexture === texture) {
  40444. return true;
  40445. }
  40446. return false;
  40447. };
  40448. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40449. if (forceDisposeTextures) {
  40450. if (this._diffuseTexture) {
  40451. this._diffuseTexture.dispose();
  40452. }
  40453. if (this._ambientTexture) {
  40454. this._ambientTexture.dispose();
  40455. }
  40456. if (this._opacityTexture) {
  40457. this._opacityTexture.dispose();
  40458. }
  40459. if (this._reflectionTexture) {
  40460. this._reflectionTexture.dispose();
  40461. }
  40462. if (this._emissiveTexture) {
  40463. this._emissiveTexture.dispose();
  40464. }
  40465. if (this._specularTexture) {
  40466. this._specularTexture.dispose();
  40467. }
  40468. if (this._bumpTexture) {
  40469. this._bumpTexture.dispose();
  40470. }
  40471. if (this._lightmapTexture) {
  40472. this._lightmapTexture.dispose();
  40473. }
  40474. if (this._refractionTexture) {
  40475. this._refractionTexture.dispose();
  40476. }
  40477. }
  40478. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40479. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40480. }
  40481. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40482. };
  40483. StandardMaterial.prototype.clone = function (name) {
  40484. var _this = this;
  40485. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40486. result.name = name;
  40487. result.id = name;
  40488. return result;
  40489. };
  40490. StandardMaterial.prototype.serialize = function () {
  40491. return BABYLON.SerializationHelper.Serialize(this);
  40492. };
  40493. // Statics
  40494. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40495. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40496. };
  40497. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40498. get: function () {
  40499. return StandardMaterial._DiffuseTextureEnabled;
  40500. },
  40501. set: function (value) {
  40502. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40503. return;
  40504. }
  40505. StandardMaterial._DiffuseTextureEnabled = value;
  40506. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40507. },
  40508. enumerable: true,
  40509. configurable: true
  40510. });
  40511. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40512. get: function () {
  40513. return StandardMaterial._AmbientTextureEnabled;
  40514. },
  40515. set: function (value) {
  40516. if (StandardMaterial._AmbientTextureEnabled === value) {
  40517. return;
  40518. }
  40519. StandardMaterial._AmbientTextureEnabled = value;
  40520. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40521. },
  40522. enumerable: true,
  40523. configurable: true
  40524. });
  40525. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40526. get: function () {
  40527. return StandardMaterial._OpacityTextureEnabled;
  40528. },
  40529. set: function (value) {
  40530. if (StandardMaterial._OpacityTextureEnabled === value) {
  40531. return;
  40532. }
  40533. StandardMaterial._OpacityTextureEnabled = value;
  40534. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40535. },
  40536. enumerable: true,
  40537. configurable: true
  40538. });
  40539. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40540. get: function () {
  40541. return StandardMaterial._ReflectionTextureEnabled;
  40542. },
  40543. set: function (value) {
  40544. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40545. return;
  40546. }
  40547. StandardMaterial._ReflectionTextureEnabled = value;
  40548. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40549. },
  40550. enumerable: true,
  40551. configurable: true
  40552. });
  40553. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40554. get: function () {
  40555. return StandardMaterial._EmissiveTextureEnabled;
  40556. },
  40557. set: function (value) {
  40558. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40559. return;
  40560. }
  40561. StandardMaterial._EmissiveTextureEnabled = value;
  40562. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40563. },
  40564. enumerable: true,
  40565. configurable: true
  40566. });
  40567. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40568. get: function () {
  40569. return StandardMaterial._SpecularTextureEnabled;
  40570. },
  40571. set: function (value) {
  40572. if (StandardMaterial._SpecularTextureEnabled === value) {
  40573. return;
  40574. }
  40575. StandardMaterial._SpecularTextureEnabled = value;
  40576. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40577. },
  40578. enumerable: true,
  40579. configurable: true
  40580. });
  40581. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40582. get: function () {
  40583. return StandardMaterial._BumpTextureEnabled;
  40584. },
  40585. set: function (value) {
  40586. if (StandardMaterial._BumpTextureEnabled === value) {
  40587. return;
  40588. }
  40589. StandardMaterial._BumpTextureEnabled = value;
  40590. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40591. },
  40592. enumerable: true,
  40593. configurable: true
  40594. });
  40595. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40596. get: function () {
  40597. return StandardMaterial._LightmapTextureEnabled;
  40598. },
  40599. set: function (value) {
  40600. if (StandardMaterial._LightmapTextureEnabled === value) {
  40601. return;
  40602. }
  40603. StandardMaterial._LightmapTextureEnabled = value;
  40604. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40605. },
  40606. enumerable: true,
  40607. configurable: true
  40608. });
  40609. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40610. get: function () {
  40611. return StandardMaterial._RefractionTextureEnabled;
  40612. },
  40613. set: function (value) {
  40614. if (StandardMaterial._RefractionTextureEnabled === value) {
  40615. return;
  40616. }
  40617. StandardMaterial._RefractionTextureEnabled = value;
  40618. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40619. },
  40620. enumerable: true,
  40621. configurable: true
  40622. });
  40623. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40624. get: function () {
  40625. return StandardMaterial._ColorGradingTextureEnabled;
  40626. },
  40627. set: function (value) {
  40628. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40629. return;
  40630. }
  40631. StandardMaterial._ColorGradingTextureEnabled = value;
  40632. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40633. },
  40634. enumerable: true,
  40635. configurable: true
  40636. });
  40637. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40638. get: function () {
  40639. return StandardMaterial._FresnelEnabled;
  40640. },
  40641. set: function (value) {
  40642. if (StandardMaterial._FresnelEnabled === value) {
  40643. return;
  40644. }
  40645. StandardMaterial._FresnelEnabled = value;
  40646. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40647. },
  40648. enumerable: true,
  40649. configurable: true
  40650. });
  40651. // Flags used to enable or disable a type of texture for all Standard Materials
  40652. StandardMaterial._DiffuseTextureEnabled = true;
  40653. StandardMaterial._AmbientTextureEnabled = true;
  40654. StandardMaterial._OpacityTextureEnabled = true;
  40655. StandardMaterial._ReflectionTextureEnabled = true;
  40656. StandardMaterial._EmissiveTextureEnabled = true;
  40657. StandardMaterial._SpecularTextureEnabled = true;
  40658. StandardMaterial._BumpTextureEnabled = true;
  40659. StandardMaterial._LightmapTextureEnabled = true;
  40660. StandardMaterial._RefractionTextureEnabled = true;
  40661. StandardMaterial._ColorGradingTextureEnabled = true;
  40662. StandardMaterial._FresnelEnabled = true;
  40663. __decorate([
  40664. BABYLON.serializeAsTexture("diffuseTexture")
  40665. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40666. __decorate([
  40667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40668. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40669. __decorate([
  40670. BABYLON.serializeAsTexture("ambientTexture")
  40671. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40672. __decorate([
  40673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40674. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40675. __decorate([
  40676. BABYLON.serializeAsTexture("opacityTexture")
  40677. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40678. __decorate([
  40679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40680. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40681. __decorate([
  40682. BABYLON.serializeAsTexture("reflectionTexture")
  40683. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40684. __decorate([
  40685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40686. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40687. __decorate([
  40688. BABYLON.serializeAsTexture("emissiveTexture")
  40689. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40690. __decorate([
  40691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40692. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40693. __decorate([
  40694. BABYLON.serializeAsTexture("specularTexture")
  40695. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40696. __decorate([
  40697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40698. ], StandardMaterial.prototype, "specularTexture", void 0);
  40699. __decorate([
  40700. BABYLON.serializeAsTexture("bumpTexture")
  40701. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40702. __decorate([
  40703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40704. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40705. __decorate([
  40706. BABYLON.serializeAsTexture("lightmapTexture")
  40707. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40708. __decorate([
  40709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40710. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40711. __decorate([
  40712. BABYLON.serializeAsTexture("refractionTexture")
  40713. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40714. __decorate([
  40715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40716. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40717. __decorate([
  40718. BABYLON.serializeAsColor3("ambient")
  40719. ], StandardMaterial.prototype, "ambientColor", void 0);
  40720. __decorate([
  40721. BABYLON.serializeAsColor3("diffuse")
  40722. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40723. __decorate([
  40724. BABYLON.serializeAsColor3("specular")
  40725. ], StandardMaterial.prototype, "specularColor", void 0);
  40726. __decorate([
  40727. BABYLON.serializeAsColor3("emissive")
  40728. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40729. __decorate([
  40730. BABYLON.serialize()
  40731. ], StandardMaterial.prototype, "specularPower", void 0);
  40732. __decorate([
  40733. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40734. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40735. __decorate([
  40736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40737. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40738. __decorate([
  40739. BABYLON.serialize("useEmissiveAsIllumination")
  40740. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40741. __decorate([
  40742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40743. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40744. __decorate([
  40745. BABYLON.serialize("linkEmissiveWithDiffuse")
  40746. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40747. __decorate([
  40748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40749. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40750. __decorate([
  40751. BABYLON.serialize("useSpecularOverAlpha")
  40752. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40753. __decorate([
  40754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40755. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40756. __decorate([
  40757. BABYLON.serialize("useReflectionOverAlpha")
  40758. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40759. __decorate([
  40760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40761. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40762. __decorate([
  40763. BABYLON.serialize("disableLighting")
  40764. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40765. __decorate([
  40766. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40767. ], StandardMaterial.prototype, "disableLighting", void 0);
  40768. __decorate([
  40769. BABYLON.serialize("useObjectSpaceNormalMap")
  40770. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40771. __decorate([
  40772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40773. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40774. __decorate([
  40775. BABYLON.serialize("useParallax")
  40776. ], StandardMaterial.prototype, "_useParallax", void 0);
  40777. __decorate([
  40778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40779. ], StandardMaterial.prototype, "useParallax", void 0);
  40780. __decorate([
  40781. BABYLON.serialize("useParallaxOcclusion")
  40782. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40783. __decorate([
  40784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40785. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40786. __decorate([
  40787. BABYLON.serialize()
  40788. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40789. __decorate([
  40790. BABYLON.serialize("roughness")
  40791. ], StandardMaterial.prototype, "_roughness", void 0);
  40792. __decorate([
  40793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40794. ], StandardMaterial.prototype, "roughness", void 0);
  40795. __decorate([
  40796. BABYLON.serialize()
  40797. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40798. __decorate([
  40799. BABYLON.serialize()
  40800. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40801. __decorate([
  40802. BABYLON.serialize("useLightmapAsShadowmap")
  40803. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40804. __decorate([
  40805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40806. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40807. __decorate([
  40808. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40809. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40810. __decorate([
  40811. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40812. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40813. __decorate([
  40814. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40815. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40816. __decorate([
  40817. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40818. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40819. __decorate([
  40820. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40821. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40822. __decorate([
  40823. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40824. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40825. __decorate([
  40826. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40827. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40828. __decorate([
  40829. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40830. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40831. __decorate([
  40832. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40833. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40834. __decorate([
  40835. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40836. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40837. __decorate([
  40838. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40839. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40840. __decorate([
  40841. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40842. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40843. __decorate([
  40844. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40845. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40846. __decorate([
  40847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40848. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40849. __decorate([
  40850. BABYLON.serialize("maxSimultaneousLights")
  40851. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40852. __decorate([
  40853. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40854. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40855. __decorate([
  40856. BABYLON.serialize("invertNormalMapX")
  40857. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40858. __decorate([
  40859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40860. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40861. __decorate([
  40862. BABYLON.serialize("invertNormalMapY")
  40863. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40864. __decorate([
  40865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40866. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40867. __decorate([
  40868. BABYLON.serialize("twoSidedLighting")
  40869. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40870. __decorate([
  40871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40872. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40873. __decorate([
  40874. BABYLON.serialize()
  40875. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40876. return StandardMaterial;
  40877. }(BABYLON.PushMaterial));
  40878. BABYLON.StandardMaterial = StandardMaterial;
  40879. })(BABYLON || (BABYLON = {}));
  40880. //# sourceMappingURL=babylon.standardMaterial.js.map
  40881. "use strict";
  40882. var BABYLON;
  40883. (function (BABYLON) {
  40884. /**
  40885. * Manages the defines for the PBR Material.
  40886. */
  40887. var PBRMaterialDefines = /** @class */ (function (_super) {
  40888. __extends(PBRMaterialDefines, _super);
  40889. /**
  40890. * Initializes the PBR Material defines.
  40891. */
  40892. function PBRMaterialDefines() {
  40893. var _this = _super.call(this) || this;
  40894. _this.PBR = true;
  40895. _this.MAINUV1 = false;
  40896. _this.MAINUV2 = false;
  40897. _this.UV1 = false;
  40898. _this.UV2 = false;
  40899. _this.ALBEDO = false;
  40900. _this.ALBEDODIRECTUV = 0;
  40901. _this.VERTEXCOLOR = false;
  40902. _this.AMBIENT = false;
  40903. _this.AMBIENTDIRECTUV = 0;
  40904. _this.AMBIENTINGRAYSCALE = false;
  40905. _this.OPACITY = false;
  40906. _this.VERTEXALPHA = false;
  40907. _this.OPACITYDIRECTUV = 0;
  40908. _this.OPACITYRGB = false;
  40909. _this.ALPHATEST = false;
  40910. _this.DEPTHPREPASS = false;
  40911. _this.ALPHABLEND = false;
  40912. _this.ALPHAFROMALBEDO = false;
  40913. _this.ALPHATESTVALUE = "0.5";
  40914. _this.SPECULAROVERALPHA = false;
  40915. _this.RADIANCEOVERALPHA = false;
  40916. _this.ALPHAFRESNEL = false;
  40917. _this.LINEARALPHAFRESNEL = false;
  40918. _this.PREMULTIPLYALPHA = false;
  40919. _this.EMISSIVE = false;
  40920. _this.EMISSIVEDIRECTUV = 0;
  40921. _this.REFLECTIVITY = false;
  40922. _this.REFLECTIVITYDIRECTUV = 0;
  40923. _this.SPECULARTERM = false;
  40924. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40925. _this.MICROSURFACEAUTOMATIC = false;
  40926. _this.LODBASEDMICROSFURACE = false;
  40927. _this.MICROSURFACEMAP = false;
  40928. _this.MICROSURFACEMAPDIRECTUV = 0;
  40929. _this.METALLICWORKFLOW = false;
  40930. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40931. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40932. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40933. _this.AOSTOREINMETALMAPRED = false;
  40934. _this.ENVIRONMENTBRDF = false;
  40935. _this.NORMAL = false;
  40936. _this.TANGENT = false;
  40937. _this.BUMP = false;
  40938. _this.BUMPDIRECTUV = 0;
  40939. _this.OBJECTSPACE_NORMALMAP = false;
  40940. _this.PARALLAX = false;
  40941. _this.PARALLAXOCCLUSION = false;
  40942. _this.NORMALXYSCALE = true;
  40943. _this.LIGHTMAP = false;
  40944. _this.LIGHTMAPDIRECTUV = 0;
  40945. _this.USELIGHTMAPASSHADOWMAP = false;
  40946. _this.GAMMALIGHTMAP = false;
  40947. _this.REFLECTION = false;
  40948. _this.REFLECTIONMAP_3D = false;
  40949. _this.REFLECTIONMAP_SPHERICAL = false;
  40950. _this.REFLECTIONMAP_PLANAR = false;
  40951. _this.REFLECTIONMAP_CUBIC = false;
  40952. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40953. _this.REFLECTIONMAP_PROJECTION = false;
  40954. _this.REFLECTIONMAP_SKYBOX = false;
  40955. _this.REFLECTIONMAP_EXPLICIT = false;
  40956. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40957. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40958. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40959. _this.INVERTCUBICMAP = false;
  40960. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40961. _this.USESPHERICALINVERTEX = false;
  40962. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40963. _this.LODINREFLECTIONALPHA = false;
  40964. _this.GAMMAREFLECTION = false;
  40965. _this.RADIANCEOCCLUSION = false;
  40966. _this.HORIZONOCCLUSION = false;
  40967. _this.REFRACTION = false;
  40968. _this.REFRACTIONMAP_3D = false;
  40969. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40970. _this.LODINREFRACTIONALPHA = false;
  40971. _this.GAMMAREFRACTION = false;
  40972. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40973. _this.INSTANCES = false;
  40974. _this.NUM_BONE_INFLUENCERS = 0;
  40975. _this.BonesPerMesh = 0;
  40976. _this.NONUNIFORMSCALING = false;
  40977. _this.MORPHTARGETS = false;
  40978. _this.MORPHTARGETS_NORMAL = false;
  40979. _this.MORPHTARGETS_TANGENT = false;
  40980. _this.NUM_MORPH_INFLUENCERS = 0;
  40981. _this.IMAGEPROCESSING = false;
  40982. _this.VIGNETTE = false;
  40983. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40984. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40985. _this.TONEMAPPING = false;
  40986. _this.CONTRAST = false;
  40987. _this.COLORCURVES = false;
  40988. _this.COLORGRADING = false;
  40989. _this.COLORGRADING3D = false;
  40990. _this.SAMPLER3DGREENDEPTH = false;
  40991. _this.SAMPLER3DBGRMAP = false;
  40992. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40993. _this.EXPOSURE = false;
  40994. _this.GRAIN = false;
  40995. _this.USEPHYSICALLIGHTFALLOFF = false;
  40996. _this.TWOSIDEDLIGHTING = false;
  40997. _this.SHADOWFLOAT = false;
  40998. _this.CLIPPLANE = false;
  40999. _this.POINTSIZE = false;
  41000. _this.FOG = false;
  41001. _this.LOGARITHMICDEPTH = false;
  41002. _this.FORCENORMALFORWARD = false;
  41003. _this.UNLIT = false;
  41004. _this.rebuild();
  41005. return _this;
  41006. }
  41007. /**
  41008. * Resets the PBR Material defines.
  41009. */
  41010. PBRMaterialDefines.prototype.reset = function () {
  41011. _super.prototype.reset.call(this);
  41012. this.ALPHATESTVALUE = "0.5";
  41013. this.PBR = true;
  41014. };
  41015. return PBRMaterialDefines;
  41016. }(BABYLON.MaterialDefines));
  41017. /**
  41018. * The Physically based material base class of BJS.
  41019. *
  41020. * This offers the main features of a standard PBR material.
  41021. * For more information, please refer to the documentation :
  41022. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41023. */
  41024. var PBRBaseMaterial = /** @class */ (function (_super) {
  41025. __extends(PBRBaseMaterial, _super);
  41026. /**
  41027. * Instantiates a new PBRMaterial instance.
  41028. *
  41029. * @param name The material name
  41030. * @param scene The scene the material will be use in.
  41031. */
  41032. function PBRBaseMaterial(name, scene) {
  41033. var _this = _super.call(this, name, scene) || this;
  41034. /**
  41035. * Intensity of the direct lights e.g. the four lights available in your scene.
  41036. * This impacts both the direct diffuse and specular highlights.
  41037. */
  41038. _this._directIntensity = 1.0;
  41039. /**
  41040. * Intensity of the emissive part of the material.
  41041. * This helps controlling the emissive effect without modifying the emissive color.
  41042. */
  41043. _this._emissiveIntensity = 1.0;
  41044. /**
  41045. * Intensity of the environment e.g. how much the environment will light the object
  41046. * either through harmonics for rough material or through the refelction for shiny ones.
  41047. */
  41048. _this._environmentIntensity = 1.0;
  41049. /**
  41050. * This is a special control allowing the reduction of the specular highlights coming from the
  41051. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41052. */
  41053. _this._specularIntensity = 1.0;
  41054. /**
  41055. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  41056. */
  41057. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  41058. /**
  41059. * Debug Control allowing disabling the bump map on this material.
  41060. */
  41061. _this._disableBumpMap = false;
  41062. /**
  41063. * AKA Occlusion Texture Intensity in other nomenclature.
  41064. */
  41065. _this._ambientTextureStrength = 1.0;
  41066. /**
  41067. * The color of a material in ambient lighting.
  41068. */
  41069. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  41070. /**
  41071. * AKA Diffuse Color in other nomenclature.
  41072. */
  41073. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  41074. /**
  41075. * AKA Specular Color in other nomenclature.
  41076. */
  41077. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41078. /**
  41079. * The color applied when light is reflected from a material.
  41080. */
  41081. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  41082. /**
  41083. * The color applied when light is emitted from a material.
  41084. */
  41085. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  41086. /**
  41087. * AKA Glossiness in other nomenclature.
  41088. */
  41089. _this._microSurface = 0.9;
  41090. /**
  41091. * source material index of refraction (IOR)' / 'destination material IOR.
  41092. */
  41093. _this._indexOfRefraction = 0.66;
  41094. /**
  41095. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41096. */
  41097. _this._invertRefractionY = false;
  41098. /**
  41099. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41100. * Materials half opaque for instance using refraction could benefit from this control.
  41101. */
  41102. _this._linkRefractionWithTransparency = false;
  41103. /**
  41104. * Specifies that the material will use the light map as a show map.
  41105. */
  41106. _this._useLightmapAsShadowmap = false;
  41107. /**
  41108. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41109. * makes the reflect vector face the model (under horizon).
  41110. */
  41111. _this._useHorizonOcclusion = true;
  41112. /**
  41113. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41114. * too much the area relying on ambient texture to define their ambient occlusion.
  41115. */
  41116. _this._useRadianceOcclusion = true;
  41117. /**
  41118. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41119. */
  41120. _this._useAlphaFromAlbedoTexture = false;
  41121. /**
  41122. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41123. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41124. */
  41125. _this._useSpecularOverAlpha = true;
  41126. /**
  41127. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41128. */
  41129. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  41130. /**
  41131. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41132. */
  41133. _this._useRoughnessFromMetallicTextureAlpha = true;
  41134. /**
  41135. * Specifies if the metallic texture contains the roughness information in its green channel.
  41136. */
  41137. _this._useRoughnessFromMetallicTextureGreen = false;
  41138. /**
  41139. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41140. */
  41141. _this._useMetallnessFromMetallicTextureBlue = false;
  41142. /**
  41143. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41144. */
  41145. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  41146. /**
  41147. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41148. */
  41149. _this._useAmbientInGrayScale = false;
  41150. /**
  41151. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41152. * The material will try to infer what glossiness each pixel should be.
  41153. */
  41154. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  41155. /**
  41156. * BJS is using an harcoded light falloff based on a manually sets up range.
  41157. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41158. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41159. */
  41160. _this._usePhysicalLightFalloff = true;
  41161. /**
  41162. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41163. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41164. */
  41165. _this._useRadianceOverAlpha = true;
  41166. /**
  41167. * Allows using an object space normal map (instead of tangent space).
  41168. */
  41169. _this._useObjectSpaceNormalMap = false;
  41170. /**
  41171. * Allows using the bump map in parallax mode.
  41172. */
  41173. _this._useParallax = false;
  41174. /**
  41175. * Allows using the bump map in parallax occlusion mode.
  41176. */
  41177. _this._useParallaxOcclusion = false;
  41178. /**
  41179. * Controls the scale bias of the parallax mode.
  41180. */
  41181. _this._parallaxScaleBias = 0.05;
  41182. /**
  41183. * If sets to true, disables all the lights affecting the material.
  41184. */
  41185. _this._disableLighting = false;
  41186. /**
  41187. * Number of Simultaneous lights allowed on the material.
  41188. */
  41189. _this._maxSimultaneousLights = 4;
  41190. /**
  41191. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  41192. */
  41193. _this._invertNormalMapX = false;
  41194. /**
  41195. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  41196. */
  41197. _this._invertNormalMapY = false;
  41198. /**
  41199. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41200. */
  41201. _this._twoSidedLighting = false;
  41202. /**
  41203. * Defines the alpha limits in alpha test mode.
  41204. */
  41205. _this._alphaCutOff = 0.4;
  41206. /**
  41207. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41208. */
  41209. _this._forceAlphaTest = false;
  41210. /**
  41211. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41212. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41213. */
  41214. _this._useAlphaFresnel = false;
  41215. /**
  41216. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41217. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41218. */
  41219. _this._useLinearAlphaFresnel = false;
  41220. /**
  41221. * The transparency mode of the material.
  41222. */
  41223. _this._transparencyMode = null;
  41224. /**
  41225. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  41226. * from cos thetav and roughness:
  41227. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  41228. */
  41229. _this._environmentBRDFTexture = null;
  41230. /**
  41231. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41232. */
  41233. _this._forceIrradianceInFragment = false;
  41234. /**
  41235. * Force normal to face away from face.
  41236. */
  41237. _this._forceNormalForward = false;
  41238. /**
  41239. * Stores the available render targets.
  41240. */
  41241. _this._renderTargets = new BABYLON.SmartArray(16);
  41242. /**
  41243. * Sets the global ambient color for the material used in lighting calculations.
  41244. */
  41245. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41246. /**
  41247. * If set to true, no lighting calculations will be applied.
  41248. */
  41249. _this._unlit = false;
  41250. // Setup the default processing configuration to the scene.
  41251. _this._attachImageProcessingConfiguration(null);
  41252. _this.getRenderTargetTextures = function () {
  41253. _this._renderTargets.reset();
  41254. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41255. _this._renderTargets.push(_this._reflectionTexture);
  41256. }
  41257. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41258. _this._renderTargets.push(_this._refractionTexture);
  41259. }
  41260. return _this._renderTargets;
  41261. };
  41262. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41263. return _this;
  41264. }
  41265. /**
  41266. * Attaches a new image processing configuration to the PBR Material.
  41267. * @param configuration
  41268. */
  41269. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41270. var _this = this;
  41271. if (configuration === this._imageProcessingConfiguration) {
  41272. return;
  41273. }
  41274. // Detaches observer.
  41275. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41276. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41277. }
  41278. // Pick the scene configuration if needed.
  41279. if (!configuration) {
  41280. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41281. }
  41282. else {
  41283. this._imageProcessingConfiguration = configuration;
  41284. }
  41285. // Attaches observer.
  41286. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41287. _this._markAllSubMeshesAsImageProcessingDirty();
  41288. });
  41289. };
  41290. /**
  41291. * Gets the name of the material class.
  41292. */
  41293. PBRBaseMaterial.prototype.getClassName = function () {
  41294. return "PBRBaseMaterial";
  41295. };
  41296. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  41297. /**
  41298. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41299. */
  41300. get: function () {
  41301. return this._useLogarithmicDepth;
  41302. },
  41303. /**
  41304. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41305. */
  41306. set: function (value) {
  41307. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41308. },
  41309. enumerable: true,
  41310. configurable: true
  41311. });
  41312. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  41313. /**
  41314. * Gets the current transparency mode.
  41315. */
  41316. get: function () {
  41317. return this._transparencyMode;
  41318. },
  41319. /**
  41320. * Sets the transparency mode of the material.
  41321. */
  41322. set: function (value) {
  41323. if (this._transparencyMode === value) {
  41324. return;
  41325. }
  41326. this._transparencyMode = value;
  41327. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  41328. this._markAllSubMeshesAsTexturesAndMiscDirty();
  41329. },
  41330. enumerable: true,
  41331. configurable: true
  41332. });
  41333. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  41334. /**
  41335. * Returns true if alpha blending should be disabled.
  41336. */
  41337. get: function () {
  41338. return (this._linkRefractionWithTransparency ||
  41339. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  41340. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41341. },
  41342. enumerable: true,
  41343. configurable: true
  41344. });
  41345. /**
  41346. * Specifies whether or not this material should be rendered in alpha blend mode.
  41347. */
  41348. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  41349. if (this._disableAlphaBlending) {
  41350. return false;
  41351. }
  41352. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  41353. };
  41354. /**
  41355. * Specifies if the mesh will require alpha blending.
  41356. * @param mesh - BJS mesh.
  41357. */
  41358. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  41359. if (this._disableAlphaBlending) {
  41360. return false;
  41361. }
  41362. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  41363. };
  41364. /**
  41365. * Specifies whether or not this material should be rendered in alpha test mode.
  41366. */
  41367. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  41368. if (this._forceAlphaTest) {
  41369. return true;
  41370. }
  41371. if (this._linkRefractionWithTransparency) {
  41372. return false;
  41373. }
  41374. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41375. };
  41376. /**
  41377. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  41378. */
  41379. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  41380. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  41381. };
  41382. /**
  41383. * Gets the texture used for the alpha test.
  41384. */
  41385. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  41386. return this._albedoTexture;
  41387. };
  41388. /**
  41389. * Specifies that the submesh is ready to be used.
  41390. * @param mesh - BJS mesh.
  41391. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  41392. * @param useInstances - Specifies that instances should be used.
  41393. * @returns - boolean indicating that the submesh is ready or not.
  41394. */
  41395. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41396. if (subMesh.effect && this.isFrozen) {
  41397. if (this._wasPreviouslyReady) {
  41398. return true;
  41399. }
  41400. }
  41401. if (!subMesh._materialDefines) {
  41402. subMesh._materialDefines = new PBRMaterialDefines();
  41403. }
  41404. var defines = subMesh._materialDefines;
  41405. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41406. if (defines._renderId === this.getScene().getRenderId()) {
  41407. return true;
  41408. }
  41409. }
  41410. var scene = this.getScene();
  41411. var engine = scene.getEngine();
  41412. if (defines._areTexturesDirty) {
  41413. if (scene.texturesEnabled) {
  41414. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41415. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  41416. return false;
  41417. }
  41418. }
  41419. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41420. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41421. return false;
  41422. }
  41423. }
  41424. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41425. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41426. return false;
  41427. }
  41428. }
  41429. var reflectionTexture = this._getReflectionTexture();
  41430. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41431. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41432. return false;
  41433. }
  41434. }
  41435. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41436. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41437. return false;
  41438. }
  41439. }
  41440. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41441. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41442. return false;
  41443. }
  41444. }
  41445. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41446. if (this._metallicTexture) {
  41447. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41448. return false;
  41449. }
  41450. }
  41451. else if (this._reflectivityTexture) {
  41452. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41453. return false;
  41454. }
  41455. }
  41456. if (this._microSurfaceTexture) {
  41457. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41458. return false;
  41459. }
  41460. }
  41461. }
  41462. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41463. // Bump texture cannot be not blocking.
  41464. if (!this._bumpTexture.isReady()) {
  41465. return false;
  41466. }
  41467. }
  41468. var refractionTexture = this._getRefractionTexture();
  41469. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41470. if (!refractionTexture.isReadyOrNotBlocking()) {
  41471. return false;
  41472. }
  41473. }
  41474. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41475. // This is blocking.
  41476. if (!this._environmentBRDFTexture.isReady()) {
  41477. return false;
  41478. }
  41479. }
  41480. }
  41481. }
  41482. if (defines._areImageProcessingDirty) {
  41483. if (!this._imageProcessingConfiguration.isReady()) {
  41484. return false;
  41485. }
  41486. }
  41487. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41488. mesh.createNormals(true);
  41489. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  41490. }
  41491. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41492. if (effect) {
  41493. scene.resetCachedMaterial();
  41494. subMesh.setEffect(effect, defines);
  41495. this.buildUniformLayout();
  41496. }
  41497. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41498. return false;
  41499. }
  41500. defines._renderId = scene.getRenderId();
  41501. this._wasPreviouslyReady = true;
  41502. return true;
  41503. };
  41504. /**
  41505. * Specifies if the material uses metallic roughness workflow.
  41506. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41507. */
  41508. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41509. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41510. return true;
  41511. }
  41512. return false;
  41513. };
  41514. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41515. if (onCompiled === void 0) { onCompiled = null; }
  41516. if (onError === void 0) { onError = null; }
  41517. if (useInstances === void 0) { useInstances = null; }
  41518. if (useClipPlane === void 0) { useClipPlane = null; }
  41519. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41520. if (!defines.isDirty) {
  41521. return null;
  41522. }
  41523. defines.markAsProcessed();
  41524. var scene = this.getScene();
  41525. var engine = scene.getEngine();
  41526. // Fallbacks
  41527. var fallbacks = new BABYLON.EffectFallbacks();
  41528. var fallbackRank = 0;
  41529. if (defines.USESPHERICALINVERTEX) {
  41530. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41531. }
  41532. if (defines.FOG) {
  41533. fallbacks.addFallback(fallbackRank, "FOG");
  41534. }
  41535. if (defines.POINTSIZE) {
  41536. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41537. }
  41538. if (defines.LOGARITHMICDEPTH) {
  41539. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41540. }
  41541. if (defines.PARALLAX) {
  41542. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41543. }
  41544. if (defines.PARALLAXOCCLUSION) {
  41545. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41546. }
  41547. if (defines.ENVIRONMENTBRDF) {
  41548. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41549. }
  41550. if (defines.TANGENT) {
  41551. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41552. }
  41553. if (defines.BUMP) {
  41554. fallbacks.addFallback(fallbackRank++, "BUMP");
  41555. }
  41556. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41557. if (defines.SPECULARTERM) {
  41558. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41559. }
  41560. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41561. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41562. }
  41563. if (defines.LIGHTMAP) {
  41564. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41565. }
  41566. if (defines.NORMAL) {
  41567. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41568. }
  41569. if (defines.AMBIENT) {
  41570. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41571. }
  41572. if (defines.EMISSIVE) {
  41573. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41574. }
  41575. if (defines.VERTEXCOLOR) {
  41576. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41577. }
  41578. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41579. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41580. }
  41581. if (defines.MORPHTARGETS) {
  41582. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41583. }
  41584. //Attributes
  41585. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41586. if (defines.NORMAL) {
  41587. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41588. }
  41589. if (defines.TANGENT) {
  41590. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41591. }
  41592. if (defines.UV1) {
  41593. attribs.push(BABYLON.VertexBuffer.UVKind);
  41594. }
  41595. if (defines.UV2) {
  41596. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41597. }
  41598. if (defines.VERTEXCOLOR) {
  41599. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41600. }
  41601. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41602. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41603. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41604. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41605. "vFogInfos", "vFogColor", "pointSize",
  41606. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41607. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41608. "mBones",
  41609. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41610. "vLightingIntensity",
  41611. "logarithmicDepthConstant",
  41612. "vSphericalX", "vSphericalY", "vSphericalZ",
  41613. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41614. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41615. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41616. "vTangentSpaceParams"
  41617. ];
  41618. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41619. "bumpSampler", "lightmapSampler", "opacitySampler",
  41620. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41621. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41622. "microSurfaceSampler", "environmentBrdfSampler"];
  41623. var uniformBuffers = ["Material", "Scene"];
  41624. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41625. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41626. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41627. uniformsNames: uniforms,
  41628. uniformBuffersNames: uniformBuffers,
  41629. samplers: samplers,
  41630. defines: defines,
  41631. maxSimultaneousLights: this._maxSimultaneousLights
  41632. });
  41633. var join = defines.toString();
  41634. return engine.createEffect("pbr", {
  41635. attributes: attribs,
  41636. uniformsNames: uniforms,
  41637. uniformBuffersNames: uniformBuffers,
  41638. samplers: samplers,
  41639. defines: join,
  41640. fallbacks: fallbacks,
  41641. onCompiled: onCompiled,
  41642. onError: onError,
  41643. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41644. }, engine);
  41645. };
  41646. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41647. if (useInstances === void 0) { useInstances = null; }
  41648. if (useClipPlane === void 0) { useClipPlane = null; }
  41649. var scene = this.getScene();
  41650. var engine = scene.getEngine();
  41651. // Lights
  41652. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41653. defines._needNormals = true;
  41654. // Textures
  41655. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41656. if (defines._areTexturesDirty) {
  41657. defines._needUVs = false;
  41658. if (scene.texturesEnabled) {
  41659. if (scene.getEngine().getCaps().textureLOD) {
  41660. defines.LODBASEDMICROSFURACE = true;
  41661. }
  41662. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41663. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41664. }
  41665. else {
  41666. defines.ALBEDO = false;
  41667. }
  41668. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41669. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41670. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41671. }
  41672. else {
  41673. defines.AMBIENT = false;
  41674. }
  41675. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41676. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41677. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41678. }
  41679. else {
  41680. defines.OPACITY = false;
  41681. }
  41682. var reflectionTexture = this._getReflectionTexture();
  41683. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41684. defines.REFLECTION = true;
  41685. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41686. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41687. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41688. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41689. defines.INVERTCUBICMAP = true;
  41690. }
  41691. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41692. switch (reflectionTexture.coordinatesMode) {
  41693. case BABYLON.Texture.CUBIC_MODE:
  41694. case BABYLON.Texture.INVCUBIC_MODE:
  41695. defines.REFLECTIONMAP_CUBIC = true;
  41696. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41697. break;
  41698. case BABYLON.Texture.EXPLICIT_MODE:
  41699. defines.REFLECTIONMAP_EXPLICIT = true;
  41700. break;
  41701. case BABYLON.Texture.PLANAR_MODE:
  41702. defines.REFLECTIONMAP_PLANAR = true;
  41703. break;
  41704. case BABYLON.Texture.PROJECTION_MODE:
  41705. defines.REFLECTIONMAP_PROJECTION = true;
  41706. break;
  41707. case BABYLON.Texture.SKYBOX_MODE:
  41708. defines.REFLECTIONMAP_SKYBOX = true;
  41709. break;
  41710. case BABYLON.Texture.SPHERICAL_MODE:
  41711. defines.REFLECTIONMAP_SPHERICAL = true;
  41712. break;
  41713. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41714. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41715. break;
  41716. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41717. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41718. break;
  41719. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41720. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41721. break;
  41722. }
  41723. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41724. if (reflectionTexture.sphericalPolynomial) {
  41725. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41726. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41727. defines.USESPHERICALINVERTEX = false;
  41728. }
  41729. else {
  41730. defines.USESPHERICALINVERTEX = true;
  41731. }
  41732. }
  41733. }
  41734. }
  41735. else {
  41736. defines.REFLECTION = false;
  41737. defines.REFLECTIONMAP_3D = false;
  41738. defines.REFLECTIONMAP_SPHERICAL = false;
  41739. defines.REFLECTIONMAP_PLANAR = false;
  41740. defines.REFLECTIONMAP_CUBIC = false;
  41741. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41742. defines.REFLECTIONMAP_PROJECTION = false;
  41743. defines.REFLECTIONMAP_SKYBOX = false;
  41744. defines.REFLECTIONMAP_EXPLICIT = false;
  41745. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41746. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41747. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41748. defines.INVERTCUBICMAP = false;
  41749. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41750. defines.USESPHERICALINVERTEX = false;
  41751. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41752. defines.LODINREFLECTIONALPHA = false;
  41753. defines.GAMMAREFLECTION = false;
  41754. }
  41755. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41756. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41757. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41758. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  41759. }
  41760. else {
  41761. defines.LIGHTMAP = false;
  41762. }
  41763. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41764. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41765. }
  41766. else {
  41767. defines.EMISSIVE = false;
  41768. }
  41769. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41770. if (this._metallicTexture) {
  41771. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41772. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41773. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41774. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41775. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41776. }
  41777. else if (this._reflectivityTexture) {
  41778. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41779. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41780. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41781. }
  41782. else {
  41783. defines.REFLECTIVITY = false;
  41784. }
  41785. if (this._microSurfaceTexture) {
  41786. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41787. }
  41788. else {
  41789. defines.MICROSURFACEMAP = false;
  41790. }
  41791. }
  41792. else {
  41793. defines.REFLECTIVITY = false;
  41794. defines.MICROSURFACEMAP = false;
  41795. }
  41796. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41797. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41798. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41799. defines.PARALLAX = true;
  41800. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41801. }
  41802. else {
  41803. defines.PARALLAX = false;
  41804. }
  41805. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41806. }
  41807. else {
  41808. defines.BUMP = false;
  41809. }
  41810. var refractionTexture = this._getRefractionTexture();
  41811. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41812. defines.REFRACTION = true;
  41813. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41814. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41815. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41816. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41817. if (this._linkRefractionWithTransparency) {
  41818. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41819. }
  41820. }
  41821. else {
  41822. defines.REFRACTION = false;
  41823. }
  41824. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41825. defines.ENVIRONMENTBRDF = true;
  41826. }
  41827. else {
  41828. defines.ENVIRONMENTBRDF = false;
  41829. }
  41830. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41831. defines.ALPHAFROMALBEDO = true;
  41832. }
  41833. else {
  41834. defines.ALPHAFROMALBEDO = false;
  41835. }
  41836. }
  41837. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41838. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41839. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41840. if (!this.backFaceCulling && this._twoSidedLighting) {
  41841. defines.TWOSIDEDLIGHTING = true;
  41842. }
  41843. else {
  41844. defines.TWOSIDEDLIGHTING = false;
  41845. }
  41846. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  41847. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41848. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41849. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41850. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41851. }
  41852. if (defines._areImageProcessingDirty) {
  41853. this._imageProcessingConfiguration.prepareDefines(defines);
  41854. }
  41855. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41856. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41857. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41858. // Misc.
  41859. if (defines._areMiscDirty) {
  41860. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41861. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41862. }
  41863. // Values that need to be evaluated on every frame
  41864. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41865. // Attribs
  41866. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41867. };
  41868. /**
  41869. * Force shader compilation
  41870. */
  41871. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41872. var _this = this;
  41873. var localOptions = __assign({ clipPlane: false }, options);
  41874. var defines = new PBRMaterialDefines();
  41875. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41876. if (effect.isReady()) {
  41877. if (onCompiled) {
  41878. onCompiled(this);
  41879. }
  41880. }
  41881. else {
  41882. effect.onCompileObservable.add(function () {
  41883. if (onCompiled) {
  41884. onCompiled(_this);
  41885. }
  41886. });
  41887. }
  41888. };
  41889. /**
  41890. * Initializes the uniform buffer layout for the shader.
  41891. */
  41892. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41893. // Order is important !
  41894. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41895. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41896. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41897. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41898. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41899. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41900. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41901. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41902. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41903. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41904. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41905. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41906. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41907. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41908. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41909. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41910. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41911. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41912. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41913. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41914. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41915. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41916. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41917. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41918. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41919. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41920. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41921. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41922. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41923. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41924. this._uniformBuffer.addUniform("pointSize", 1);
  41925. this._uniformBuffer.create();
  41926. };
  41927. /**
  41928. * Unbinds the textures.
  41929. */
  41930. PBRBaseMaterial.prototype.unbind = function () {
  41931. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41932. this._uniformBuffer.setTexture("reflectionSampler", null);
  41933. }
  41934. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41935. this._uniformBuffer.setTexture("refractionSampler", null);
  41936. }
  41937. _super.prototype.unbind.call(this);
  41938. };
  41939. /**
  41940. * Binds the submesh data.
  41941. * @param world - The world matrix.
  41942. * @param mesh - The BJS mesh.
  41943. * @param subMesh - A submesh of the BJS mesh.
  41944. */
  41945. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41946. var scene = this.getScene();
  41947. var defines = subMesh._materialDefines;
  41948. if (!defines) {
  41949. return;
  41950. }
  41951. var effect = subMesh.effect;
  41952. if (!effect) {
  41953. return;
  41954. }
  41955. this._activeEffect = effect;
  41956. // Matrices
  41957. this.bindOnlyWorldMatrix(world);
  41958. // Normal Matrix
  41959. if (defines.OBJECTSPACE_NORMALMAP) {
  41960. world.toNormalMatrix(this._normalMatrix);
  41961. this.bindOnlyNormalMatrix(this._normalMatrix);
  41962. }
  41963. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41964. // Bones
  41965. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41966. var reflectionTexture = null;
  41967. if (mustRebind) {
  41968. this._uniformBuffer.bindToEffect(effect, "Material");
  41969. this.bindViewProjection(effect);
  41970. reflectionTexture = this._getReflectionTexture();
  41971. var refractionTexture = this._getRefractionTexture();
  41972. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41973. // Texture uniforms
  41974. if (scene.texturesEnabled) {
  41975. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41976. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41977. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41978. }
  41979. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41980. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41981. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41982. }
  41983. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41984. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41985. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41986. }
  41987. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41988. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41989. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41990. if (reflectionTexture.boundingBoxSize) {
  41991. var cubeTexture = reflectionTexture;
  41992. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41993. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41994. }
  41995. var polynomials = reflectionTexture.sphericalPolynomial;
  41996. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41997. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41998. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41999. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  42000. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  42001. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  42002. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  42003. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  42004. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  42005. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  42006. }
  42007. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  42008. }
  42009. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42010. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42011. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42012. }
  42013. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42014. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42015. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42016. }
  42017. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42018. if (this._metallicTexture) {
  42019. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  42020. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  42021. }
  42022. else if (this._reflectivityTexture) {
  42023. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  42024. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  42025. }
  42026. if (this._microSurfaceTexture) {
  42027. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  42028. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  42029. }
  42030. }
  42031. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42032. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  42033. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42034. if (scene._mirroredCameraPosition) {
  42035. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42036. }
  42037. else {
  42038. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42039. }
  42040. }
  42041. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42042. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  42043. var depth = 1.0;
  42044. if (!refractionTexture.isCube) {
  42045. if (refractionTexture.depth) {
  42046. depth = refractionTexture.depth;
  42047. }
  42048. }
  42049. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  42050. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  42051. }
  42052. }
  42053. // Point size
  42054. if (this.pointsCloud) {
  42055. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42056. }
  42057. // Colors
  42058. if (defines.METALLICWORKFLOW) {
  42059. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  42060. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  42061. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  42062. }
  42063. else {
  42064. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  42065. }
  42066. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  42067. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  42068. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  42069. // Misc
  42070. this._lightingInfos.x = this._directIntensity;
  42071. this._lightingInfos.y = this._emissiveIntensity;
  42072. this._lightingInfos.z = this._environmentIntensity;
  42073. this._lightingInfos.w = this._specularIntensity;
  42074. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  42075. }
  42076. // Textures
  42077. if (scene.texturesEnabled) {
  42078. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42079. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  42080. }
  42081. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42082. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  42083. }
  42084. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42085. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  42086. }
  42087. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42088. if (defines.LODBASEDMICROSFURACE) {
  42089. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  42090. }
  42091. else {
  42092. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  42093. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  42094. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  42095. }
  42096. }
  42097. if (defines.ENVIRONMENTBRDF) {
  42098. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  42099. }
  42100. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42101. if (defines.LODBASEDMICROSFURACE) {
  42102. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  42103. }
  42104. else {
  42105. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  42106. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  42107. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  42108. }
  42109. }
  42110. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42111. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  42112. }
  42113. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42114. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  42115. }
  42116. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42117. if (this._metallicTexture) {
  42118. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  42119. }
  42120. else if (this._reflectivityTexture) {
  42121. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  42122. }
  42123. if (this._microSurfaceTexture) {
  42124. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  42125. }
  42126. }
  42127. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42128. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  42129. }
  42130. }
  42131. // Clip plane
  42132. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  42133. // Colors
  42134. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  42135. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42136. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  42137. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  42138. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42139. }
  42140. if (mustRebind || !this.isFrozen) {
  42141. // Lights
  42142. if (scene.lightsEnabled && !this._disableLighting) {
  42143. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  42144. }
  42145. // View
  42146. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  42147. this.bindView(effect);
  42148. }
  42149. // Fog
  42150. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  42151. // Morph targets
  42152. if (defines.NUM_MORPH_INFLUENCERS) {
  42153. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  42154. }
  42155. // image processing
  42156. this._imageProcessingConfiguration.bind(this._activeEffect);
  42157. // Log. depth
  42158. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  42159. }
  42160. this._uniformBuffer.update();
  42161. this._afterBind(mesh);
  42162. };
  42163. /**
  42164. * Returns the animatable textures.
  42165. * @returns - Array of animatable textures.
  42166. */
  42167. PBRBaseMaterial.prototype.getAnimatables = function () {
  42168. var results = [];
  42169. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  42170. results.push(this._albedoTexture);
  42171. }
  42172. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42173. results.push(this._ambientTexture);
  42174. }
  42175. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42176. results.push(this._opacityTexture);
  42177. }
  42178. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42179. results.push(this._reflectionTexture);
  42180. }
  42181. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42182. results.push(this._emissiveTexture);
  42183. }
  42184. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  42185. results.push(this._metallicTexture);
  42186. }
  42187. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  42188. results.push(this._reflectivityTexture);
  42189. }
  42190. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42191. results.push(this._bumpTexture);
  42192. }
  42193. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42194. results.push(this._lightmapTexture);
  42195. }
  42196. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42197. results.push(this._refractionTexture);
  42198. }
  42199. return results;
  42200. };
  42201. /**
  42202. * Returns the texture used for reflections.
  42203. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  42204. */
  42205. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  42206. if (this._reflectionTexture) {
  42207. return this._reflectionTexture;
  42208. }
  42209. return this.getScene().environmentTexture;
  42210. };
  42211. /**
  42212. * Returns the texture used for refraction or null if none is used.
  42213. * @returns - Refection texture if present. If no refraction texture and refraction
  42214. * is linked with transparency, returns environment texture. Otherwise, returns null.
  42215. */
  42216. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  42217. if (this._refractionTexture) {
  42218. return this._refractionTexture;
  42219. }
  42220. if (this._linkRefractionWithTransparency) {
  42221. return this.getScene().environmentTexture;
  42222. }
  42223. return null;
  42224. };
  42225. /**
  42226. * Disposes the resources of the material.
  42227. * @param forceDisposeEffect - Forces the disposal of effects.
  42228. * @param forceDisposeTextures - Forces the disposal of all textures.
  42229. */
  42230. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42231. if (forceDisposeTextures) {
  42232. if (this._albedoTexture) {
  42233. this._albedoTexture.dispose();
  42234. }
  42235. if (this._ambientTexture) {
  42236. this._ambientTexture.dispose();
  42237. }
  42238. if (this._opacityTexture) {
  42239. this._opacityTexture.dispose();
  42240. }
  42241. if (this._reflectionTexture) {
  42242. this._reflectionTexture.dispose();
  42243. }
  42244. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  42245. this._environmentBRDFTexture.dispose();
  42246. }
  42247. if (this._emissiveTexture) {
  42248. this._emissiveTexture.dispose();
  42249. }
  42250. if (this._metallicTexture) {
  42251. this._metallicTexture.dispose();
  42252. }
  42253. if (this._reflectivityTexture) {
  42254. this._reflectivityTexture.dispose();
  42255. }
  42256. if (this._bumpTexture) {
  42257. this._bumpTexture.dispose();
  42258. }
  42259. if (this._lightmapTexture) {
  42260. this._lightmapTexture.dispose();
  42261. }
  42262. if (this._refractionTexture) {
  42263. this._refractionTexture.dispose();
  42264. }
  42265. }
  42266. this._renderTargets.dispose();
  42267. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42268. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42269. }
  42270. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42271. };
  42272. /**
  42273. * Stores the reflectivity values based on metallic roughness workflow.
  42274. */
  42275. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  42276. __decorate([
  42277. BABYLON.serializeAsImageProcessingConfiguration()
  42278. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  42279. __decorate([
  42280. BABYLON.serialize()
  42281. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  42282. __decorate([
  42283. BABYLON.serialize()
  42284. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  42285. return PBRBaseMaterial;
  42286. }(BABYLON.PushMaterial));
  42287. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  42288. })(BABYLON || (BABYLON = {}));
  42289. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  42290. "use strict";
  42291. var BABYLON;
  42292. (function (BABYLON) {
  42293. /**
  42294. * The Physically based simple base material of BJS.
  42295. *
  42296. * This enables better naming and convention enforcements on top of the pbrMaterial.
  42297. * It is used as the base class for both the specGloss and metalRough conventions.
  42298. */
  42299. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  42300. __extends(PBRBaseSimpleMaterial, _super);
  42301. /**
  42302. * Instantiates a new PBRMaterial instance.
  42303. *
  42304. * @param name The material name
  42305. * @param scene The scene the material will be use in.
  42306. */
  42307. function PBRBaseSimpleMaterial(name, scene) {
  42308. var _this = _super.call(this, name, scene) || this;
  42309. /**
  42310. * Number of Simultaneous lights allowed on the material.
  42311. */
  42312. _this.maxSimultaneousLights = 4;
  42313. /**
  42314. * If sets to true, disables all the lights affecting the material.
  42315. */
  42316. _this.disableLighting = false;
  42317. /**
  42318. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42319. */
  42320. _this.invertNormalMapX = false;
  42321. /**
  42322. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42323. */
  42324. _this.invertNormalMapY = false;
  42325. /**
  42326. * Emissivie color used to self-illuminate the model.
  42327. */
  42328. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42329. /**
  42330. * Occlusion Channel Strenght.
  42331. */
  42332. _this.occlusionStrength = 1.0;
  42333. _this.useLightmapAsShadowmap = false;
  42334. _this._useAlphaFromAlbedoTexture = true;
  42335. _this._useAmbientInGrayScale = true;
  42336. return _this;
  42337. }
  42338. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  42339. /**
  42340. * Gets the current double sided mode.
  42341. */
  42342. get: function () {
  42343. return this._twoSidedLighting;
  42344. },
  42345. /**
  42346. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42347. */
  42348. set: function (value) {
  42349. if (this._twoSidedLighting === value) {
  42350. return;
  42351. }
  42352. this._twoSidedLighting = value;
  42353. this.backFaceCulling = !value;
  42354. this._markAllSubMeshesAsTexturesDirty();
  42355. },
  42356. enumerable: true,
  42357. configurable: true
  42358. });
  42359. /**
  42360. * Return the active textures of the material.
  42361. */
  42362. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  42363. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42364. if (this.environmentTexture) {
  42365. activeTextures.push(this.environmentTexture);
  42366. }
  42367. if (this.normalTexture) {
  42368. activeTextures.push(this.normalTexture);
  42369. }
  42370. if (this.emissiveTexture) {
  42371. activeTextures.push(this.emissiveTexture);
  42372. }
  42373. if (this.occlusionTexture) {
  42374. activeTextures.push(this.occlusionTexture);
  42375. }
  42376. if (this.lightmapTexture) {
  42377. activeTextures.push(this.lightmapTexture);
  42378. }
  42379. return activeTextures;
  42380. };
  42381. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  42382. if (_super.prototype.hasTexture.call(this, texture)) {
  42383. return true;
  42384. }
  42385. if (this.lightmapTexture === texture) {
  42386. return true;
  42387. }
  42388. return false;
  42389. };
  42390. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  42391. return "PBRBaseSimpleMaterial";
  42392. };
  42393. __decorate([
  42394. BABYLON.serialize(),
  42395. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42396. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  42397. __decorate([
  42398. BABYLON.serialize(),
  42399. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42400. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  42401. __decorate([
  42402. BABYLON.serializeAsTexture(),
  42403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  42404. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  42405. __decorate([
  42406. BABYLON.serialize(),
  42407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42408. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  42409. __decorate([
  42410. BABYLON.serialize(),
  42411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42412. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42413. __decorate([
  42414. BABYLON.serializeAsTexture(),
  42415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42416. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42417. __decorate([
  42418. BABYLON.serializeAsColor3("emissive"),
  42419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42420. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42421. __decorate([
  42422. BABYLON.serializeAsTexture(),
  42423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42424. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42425. __decorate([
  42426. BABYLON.serialize(),
  42427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42428. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42429. __decorate([
  42430. BABYLON.serializeAsTexture(),
  42431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42432. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42433. __decorate([
  42434. BABYLON.serialize(),
  42435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42436. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42437. __decorate([
  42438. BABYLON.serialize()
  42439. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42440. __decorate([
  42441. BABYLON.serializeAsTexture(),
  42442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42443. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42444. __decorate([
  42445. BABYLON.serialize(),
  42446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42447. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42448. return PBRBaseSimpleMaterial;
  42449. }(BABYLON.PBRBaseMaterial));
  42450. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42451. })(BABYLON || (BABYLON = {}));
  42452. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42453. "use strict";
  42454. var BABYLON;
  42455. (function (BABYLON) {
  42456. /**
  42457. * The Physically based material of BJS.
  42458. *
  42459. * This offers the main features of a standard PBR material.
  42460. * For more information, please refer to the documentation :
  42461. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42462. */
  42463. var PBRMaterial = /** @class */ (function (_super) {
  42464. __extends(PBRMaterial, _super);
  42465. /**
  42466. * Instantiates a new PBRMaterial instance.
  42467. *
  42468. * @param name The material name
  42469. * @param scene The scene the material will be use in.
  42470. */
  42471. function PBRMaterial(name, scene) {
  42472. var _this = _super.call(this, name, scene) || this;
  42473. /**
  42474. * Intensity of the direct lights e.g. the four lights available in your scene.
  42475. * This impacts both the direct diffuse and specular highlights.
  42476. */
  42477. _this.directIntensity = 1.0;
  42478. /**
  42479. * Intensity of the emissive part of the material.
  42480. * This helps controlling the emissive effect without modifying the emissive color.
  42481. */
  42482. _this.emissiveIntensity = 1.0;
  42483. /**
  42484. * Intensity of the environment e.g. how much the environment will light the object
  42485. * either through harmonics for rough material or through the refelction for shiny ones.
  42486. */
  42487. _this.environmentIntensity = 1.0;
  42488. /**
  42489. * This is a special control allowing the reduction of the specular highlights coming from the
  42490. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42491. */
  42492. _this.specularIntensity = 1.0;
  42493. /**
  42494. * Debug Control allowing disabling the bump map on this material.
  42495. */
  42496. _this.disableBumpMap = false;
  42497. /**
  42498. * AKA Occlusion Texture Intensity in other nomenclature.
  42499. */
  42500. _this.ambientTextureStrength = 1.0;
  42501. /**
  42502. * The color of a material in ambient lighting.
  42503. */
  42504. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42505. /**
  42506. * AKA Diffuse Color in other nomenclature.
  42507. */
  42508. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42509. /**
  42510. * AKA Specular Color in other nomenclature.
  42511. */
  42512. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42513. /**
  42514. * The color reflected from the material.
  42515. */
  42516. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42517. /**
  42518. * The color emitted from the material.
  42519. */
  42520. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42521. /**
  42522. * AKA Glossiness in other nomenclature.
  42523. */
  42524. _this.microSurface = 1.0;
  42525. /**
  42526. * source material index of refraction (IOR)' / 'destination material IOR.
  42527. */
  42528. _this.indexOfRefraction = 0.66;
  42529. /**
  42530. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42531. */
  42532. _this.invertRefractionY = false;
  42533. /**
  42534. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42535. * Materials half opaque for instance using refraction could benefit from this control.
  42536. */
  42537. _this.linkRefractionWithTransparency = false;
  42538. _this.useLightmapAsShadowmap = false;
  42539. /**
  42540. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42541. */
  42542. _this.useAlphaFromAlbedoTexture = false;
  42543. /**
  42544. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42545. */
  42546. _this.forceAlphaTest = false;
  42547. /**
  42548. * Defines the alpha limits in alpha test mode.
  42549. */
  42550. _this.alphaCutOff = 0.4;
  42551. /**
  42552. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42553. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42554. */
  42555. _this.useSpecularOverAlpha = true;
  42556. /**
  42557. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42558. */
  42559. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42560. /**
  42561. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42562. */
  42563. _this.useRoughnessFromMetallicTextureAlpha = true;
  42564. /**
  42565. * Specifies if the metallic texture contains the roughness information in its green channel.
  42566. */
  42567. _this.useRoughnessFromMetallicTextureGreen = false;
  42568. /**
  42569. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42570. */
  42571. _this.useMetallnessFromMetallicTextureBlue = false;
  42572. /**
  42573. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42574. */
  42575. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42576. /**
  42577. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42578. */
  42579. _this.useAmbientInGrayScale = false;
  42580. /**
  42581. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42582. * The material will try to infer what glossiness each pixel should be.
  42583. */
  42584. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42585. /**
  42586. * BJS is using an harcoded light falloff based on a manually sets up range.
  42587. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42588. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42589. */
  42590. _this.usePhysicalLightFalloff = true;
  42591. /**
  42592. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42593. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42594. */
  42595. _this.useRadianceOverAlpha = true;
  42596. /**
  42597. * Allows using an object space normal map (instead of tangent space).
  42598. */
  42599. _this.useObjectSpaceNormalMap = false;
  42600. /**
  42601. * Allows using the bump map in parallax mode.
  42602. */
  42603. _this.useParallax = false;
  42604. /**
  42605. * Allows using the bump map in parallax occlusion mode.
  42606. */
  42607. _this.useParallaxOcclusion = false;
  42608. /**
  42609. * Controls the scale bias of the parallax mode.
  42610. */
  42611. _this.parallaxScaleBias = 0.05;
  42612. /**
  42613. * If sets to true, disables all the lights affecting the material.
  42614. */
  42615. _this.disableLighting = false;
  42616. /**
  42617. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42618. */
  42619. _this.forceIrradianceInFragment = false;
  42620. /**
  42621. * Number of Simultaneous lights allowed on the material.
  42622. */
  42623. _this.maxSimultaneousLights = 4;
  42624. /**
  42625. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42626. */
  42627. _this.invertNormalMapX = false;
  42628. /**
  42629. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42630. */
  42631. _this.invertNormalMapY = false;
  42632. /**
  42633. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42634. */
  42635. _this.twoSidedLighting = false;
  42636. /**
  42637. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42638. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42639. */
  42640. _this.useAlphaFresnel = false;
  42641. /**
  42642. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42643. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42644. */
  42645. _this.useLinearAlphaFresnel = false;
  42646. /**
  42647. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42648. * And/Or occlude the blended part.
  42649. */
  42650. _this.environmentBRDFTexture = null;
  42651. /**
  42652. * Force normal to face away from face.
  42653. */
  42654. _this.forceNormalForward = false;
  42655. /**
  42656. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42657. * makes the reflect vector face the model (under horizon).
  42658. */
  42659. _this.useHorizonOcclusion = true;
  42660. /**
  42661. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42662. * too much the area relying on ambient texture to define their ambient occlusion.
  42663. */
  42664. _this.useRadianceOcclusion = true;
  42665. /**
  42666. * If set to true, no lighting calculations will be applied.
  42667. */
  42668. _this.unlit = false;
  42669. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42670. return _this;
  42671. }
  42672. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42673. /**
  42674. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42675. */
  42676. get: function () {
  42677. return this._PBRMATERIAL_OPAQUE;
  42678. },
  42679. enumerable: true,
  42680. configurable: true
  42681. });
  42682. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42683. /**
  42684. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42685. */
  42686. get: function () {
  42687. return this._PBRMATERIAL_ALPHATEST;
  42688. },
  42689. enumerable: true,
  42690. configurable: true
  42691. });
  42692. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42693. /**
  42694. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42695. */
  42696. get: function () {
  42697. return this._PBRMATERIAL_ALPHABLEND;
  42698. },
  42699. enumerable: true,
  42700. configurable: true
  42701. });
  42702. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42703. /**
  42704. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42705. * They are also discarded below the alpha cutoff threshold to improve performances.
  42706. */
  42707. get: function () {
  42708. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42709. },
  42710. enumerable: true,
  42711. configurable: true
  42712. });
  42713. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42714. /**
  42715. * Gets the image processing configuration used either in this material.
  42716. */
  42717. get: function () {
  42718. return this._imageProcessingConfiguration;
  42719. },
  42720. /**
  42721. * Sets the Default image processing configuration used either in the this material.
  42722. *
  42723. * If sets to null, the scene one is in use.
  42724. */
  42725. set: function (value) {
  42726. this._attachImageProcessingConfiguration(value);
  42727. // Ensure the effect will be rebuilt.
  42728. this._markAllSubMeshesAsTexturesDirty();
  42729. },
  42730. enumerable: true,
  42731. configurable: true
  42732. });
  42733. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42734. /**
  42735. * Gets wether the color curves effect is enabled.
  42736. */
  42737. get: function () {
  42738. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42739. },
  42740. /**
  42741. * Sets wether the color curves effect is enabled.
  42742. */
  42743. set: function (value) {
  42744. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42745. },
  42746. enumerable: true,
  42747. configurable: true
  42748. });
  42749. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42750. /**
  42751. * Gets wether the color grading effect is enabled.
  42752. */
  42753. get: function () {
  42754. return this.imageProcessingConfiguration.colorGradingEnabled;
  42755. },
  42756. /**
  42757. * Gets wether the color grading effect is enabled.
  42758. */
  42759. set: function (value) {
  42760. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42761. },
  42762. enumerable: true,
  42763. configurable: true
  42764. });
  42765. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42766. /**
  42767. * Gets wether tonemapping is enabled or not.
  42768. */
  42769. get: function () {
  42770. return this._imageProcessingConfiguration.toneMappingEnabled;
  42771. },
  42772. /**
  42773. * Sets wether tonemapping is enabled or not
  42774. */
  42775. set: function (value) {
  42776. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42777. },
  42778. enumerable: true,
  42779. configurable: true
  42780. });
  42781. ;
  42782. ;
  42783. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42784. /**
  42785. * The camera exposure used on this material.
  42786. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42787. * This corresponds to a photographic exposure.
  42788. */
  42789. get: function () {
  42790. return this._imageProcessingConfiguration.exposure;
  42791. },
  42792. /**
  42793. * The camera exposure used on this material.
  42794. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42795. * This corresponds to a photographic exposure.
  42796. */
  42797. set: function (value) {
  42798. this._imageProcessingConfiguration.exposure = value;
  42799. },
  42800. enumerable: true,
  42801. configurable: true
  42802. });
  42803. ;
  42804. ;
  42805. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42806. /**
  42807. * Gets The camera contrast used on this material.
  42808. */
  42809. get: function () {
  42810. return this._imageProcessingConfiguration.contrast;
  42811. },
  42812. /**
  42813. * Sets The camera contrast used on this material.
  42814. */
  42815. set: function (value) {
  42816. this._imageProcessingConfiguration.contrast = value;
  42817. },
  42818. enumerable: true,
  42819. configurable: true
  42820. });
  42821. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42822. /**
  42823. * Gets the Color Grading 2D Lookup Texture.
  42824. */
  42825. get: function () {
  42826. return this._imageProcessingConfiguration.colorGradingTexture;
  42827. },
  42828. /**
  42829. * Sets the Color Grading 2D Lookup Texture.
  42830. */
  42831. set: function (value) {
  42832. this._imageProcessingConfiguration.colorGradingTexture = value;
  42833. },
  42834. enumerable: true,
  42835. configurable: true
  42836. });
  42837. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42838. /**
  42839. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42840. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42841. * 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;
  42842. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42843. */
  42844. get: function () {
  42845. return this._imageProcessingConfiguration.colorCurves;
  42846. },
  42847. /**
  42848. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42849. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42850. * 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;
  42851. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42852. */
  42853. set: function (value) {
  42854. this._imageProcessingConfiguration.colorCurves = value;
  42855. },
  42856. enumerable: true,
  42857. configurable: true
  42858. });
  42859. /**
  42860. * Returns the name of this material class.
  42861. */
  42862. PBRMaterial.prototype.getClassName = function () {
  42863. return "PBRMaterial";
  42864. };
  42865. /**
  42866. * Returns an array of the actively used textures.
  42867. * @returns - Array of BaseTextures
  42868. */
  42869. PBRMaterial.prototype.getActiveTextures = function () {
  42870. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42871. if (this._albedoTexture) {
  42872. activeTextures.push(this._albedoTexture);
  42873. }
  42874. if (this._ambientTexture) {
  42875. activeTextures.push(this._ambientTexture);
  42876. }
  42877. if (this._opacityTexture) {
  42878. activeTextures.push(this._opacityTexture);
  42879. }
  42880. if (this._reflectionTexture) {
  42881. activeTextures.push(this._reflectionTexture);
  42882. }
  42883. if (this._emissiveTexture) {
  42884. activeTextures.push(this._emissiveTexture);
  42885. }
  42886. if (this._reflectivityTexture) {
  42887. activeTextures.push(this._reflectivityTexture);
  42888. }
  42889. if (this._metallicTexture) {
  42890. activeTextures.push(this._metallicTexture);
  42891. }
  42892. if (this._microSurfaceTexture) {
  42893. activeTextures.push(this._microSurfaceTexture);
  42894. }
  42895. if (this._bumpTexture) {
  42896. activeTextures.push(this._bumpTexture);
  42897. }
  42898. if (this._lightmapTexture) {
  42899. activeTextures.push(this._lightmapTexture);
  42900. }
  42901. if (this._refractionTexture) {
  42902. activeTextures.push(this._refractionTexture);
  42903. }
  42904. return activeTextures;
  42905. };
  42906. /**
  42907. * Checks to see if a texture is used in the material.
  42908. * @param texture - Base texture to use.
  42909. * @returns - Boolean specifying if a texture is used in the material.
  42910. */
  42911. PBRMaterial.prototype.hasTexture = function (texture) {
  42912. if (_super.prototype.hasTexture.call(this, texture)) {
  42913. return true;
  42914. }
  42915. if (this._albedoTexture === texture) {
  42916. return true;
  42917. }
  42918. if (this._ambientTexture === texture) {
  42919. return true;
  42920. }
  42921. if (this._opacityTexture === texture) {
  42922. return true;
  42923. }
  42924. if (this._reflectionTexture === texture) {
  42925. return true;
  42926. }
  42927. if (this._reflectivityTexture === texture) {
  42928. return true;
  42929. }
  42930. if (this._metallicTexture === texture) {
  42931. return true;
  42932. }
  42933. if (this._microSurfaceTexture === texture) {
  42934. return true;
  42935. }
  42936. if (this._bumpTexture === texture) {
  42937. return true;
  42938. }
  42939. if (this._lightmapTexture === texture) {
  42940. return true;
  42941. }
  42942. if (this._refractionTexture === texture) {
  42943. return true;
  42944. }
  42945. return false;
  42946. };
  42947. /**
  42948. * Makes a duplicate of the current material.
  42949. * @param name - name to use for the new material.
  42950. */
  42951. PBRMaterial.prototype.clone = function (name) {
  42952. var _this = this;
  42953. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42954. clone.id = name;
  42955. clone.name = name;
  42956. return clone;
  42957. };
  42958. /**
  42959. * Serializes this PBR Material.
  42960. * @returns - An object with the serialized material.
  42961. */
  42962. PBRMaterial.prototype.serialize = function () {
  42963. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42964. serializationObject.customType = "BABYLON.PBRMaterial";
  42965. return serializationObject;
  42966. };
  42967. // Statics
  42968. /**
  42969. * Parses a PBR Material from a serialized object.
  42970. * @param source - Serialized object.
  42971. * @param scene - BJS scene instance.
  42972. * @param rootUrl - url for the scene object
  42973. * @returns - PBRMaterial
  42974. */
  42975. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42976. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42977. };
  42978. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42979. /**
  42980. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42981. */
  42982. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42983. /**
  42984. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42985. */
  42986. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42987. /**
  42988. * 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.
  42989. * They are also discarded below the alpha cutoff threshold to improve performances.
  42990. */
  42991. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42992. __decorate([
  42993. BABYLON.serialize(),
  42994. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42995. ], PBRMaterial.prototype, "directIntensity", void 0);
  42996. __decorate([
  42997. BABYLON.serialize(),
  42998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42999. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  43000. __decorate([
  43001. BABYLON.serialize(),
  43002. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43003. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  43004. __decorate([
  43005. BABYLON.serialize(),
  43006. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43007. ], PBRMaterial.prototype, "specularIntensity", void 0);
  43008. __decorate([
  43009. BABYLON.serialize(),
  43010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43011. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  43012. __decorate([
  43013. BABYLON.serializeAsTexture(),
  43014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43015. ], PBRMaterial.prototype, "albedoTexture", void 0);
  43016. __decorate([
  43017. BABYLON.serializeAsTexture(),
  43018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43019. ], PBRMaterial.prototype, "ambientTexture", void 0);
  43020. __decorate([
  43021. BABYLON.serialize(),
  43022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43023. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  43024. __decorate([
  43025. BABYLON.serializeAsTexture(),
  43026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43027. ], PBRMaterial.prototype, "opacityTexture", void 0);
  43028. __decorate([
  43029. BABYLON.serializeAsTexture(),
  43030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43031. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  43032. __decorate([
  43033. BABYLON.serializeAsTexture(),
  43034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43035. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  43036. __decorate([
  43037. BABYLON.serializeAsTexture(),
  43038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43039. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  43040. __decorate([
  43041. BABYLON.serializeAsTexture(),
  43042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43043. ], PBRMaterial.prototype, "metallicTexture", void 0);
  43044. __decorate([
  43045. BABYLON.serialize(),
  43046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43047. ], PBRMaterial.prototype, "metallic", void 0);
  43048. __decorate([
  43049. BABYLON.serialize(),
  43050. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43051. ], PBRMaterial.prototype, "roughness", void 0);
  43052. __decorate([
  43053. BABYLON.serializeAsTexture(),
  43054. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43055. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  43056. __decorate([
  43057. BABYLON.serializeAsTexture(),
  43058. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43059. ], PBRMaterial.prototype, "bumpTexture", void 0);
  43060. __decorate([
  43061. BABYLON.serializeAsTexture(),
  43062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  43063. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  43064. __decorate([
  43065. BABYLON.serializeAsTexture(),
  43066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43067. ], PBRMaterial.prototype, "refractionTexture", void 0);
  43068. __decorate([
  43069. BABYLON.serializeAsColor3("ambient"),
  43070. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43071. ], PBRMaterial.prototype, "ambientColor", void 0);
  43072. __decorate([
  43073. BABYLON.serializeAsColor3("albedo"),
  43074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43075. ], PBRMaterial.prototype, "albedoColor", void 0);
  43076. __decorate([
  43077. BABYLON.serializeAsColor3("reflectivity"),
  43078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43079. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  43080. __decorate([
  43081. BABYLON.serializeAsColor3("reflection"),
  43082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43083. ], PBRMaterial.prototype, "reflectionColor", void 0);
  43084. __decorate([
  43085. BABYLON.serializeAsColor3("emissive"),
  43086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43087. ], PBRMaterial.prototype, "emissiveColor", void 0);
  43088. __decorate([
  43089. BABYLON.serialize(),
  43090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43091. ], PBRMaterial.prototype, "microSurface", void 0);
  43092. __decorate([
  43093. BABYLON.serialize(),
  43094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43095. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  43096. __decorate([
  43097. BABYLON.serialize(),
  43098. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43099. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  43100. __decorate([
  43101. BABYLON.serialize(),
  43102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43103. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  43104. __decorate([
  43105. BABYLON.serialize(),
  43106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43107. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43108. __decorate([
  43109. BABYLON.serialize(),
  43110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43111. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  43112. __decorate([
  43113. BABYLON.serialize(),
  43114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43115. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  43116. __decorate([
  43117. BABYLON.serialize(),
  43118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43119. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  43120. __decorate([
  43121. BABYLON.serialize(),
  43122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43123. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  43124. __decorate([
  43125. BABYLON.serialize(),
  43126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43127. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  43128. __decorate([
  43129. BABYLON.serialize(),
  43130. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43131. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  43132. __decorate([
  43133. BABYLON.serialize(),
  43134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43135. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  43136. __decorate([
  43137. BABYLON.serialize(),
  43138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43139. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  43140. __decorate([
  43141. BABYLON.serialize(),
  43142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43143. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  43144. __decorate([
  43145. BABYLON.serialize(),
  43146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43147. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  43148. __decorate([
  43149. BABYLON.serialize(),
  43150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43151. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  43152. __decorate([
  43153. BABYLON.serialize(),
  43154. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43155. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  43156. __decorate([
  43157. BABYLON.serialize(),
  43158. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43159. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  43160. __decorate([
  43161. BABYLON.serialize(),
  43162. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43163. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43164. __decorate([
  43165. BABYLON.serialize(),
  43166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43167. ], PBRMaterial.prototype, "useParallax", void 0);
  43168. __decorate([
  43169. BABYLON.serialize(),
  43170. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43171. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  43172. __decorate([
  43173. BABYLON.serialize(),
  43174. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43175. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  43176. __decorate([
  43177. BABYLON.serialize(),
  43178. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43179. ], PBRMaterial.prototype, "disableLighting", void 0);
  43180. __decorate([
  43181. BABYLON.serialize(),
  43182. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43183. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  43184. __decorate([
  43185. BABYLON.serialize(),
  43186. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43187. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  43188. __decorate([
  43189. BABYLON.serialize(),
  43190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43191. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  43192. __decorate([
  43193. BABYLON.serialize(),
  43194. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43195. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  43196. __decorate([
  43197. BABYLON.serialize(),
  43198. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43199. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  43200. __decorate([
  43201. BABYLON.serialize(),
  43202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43203. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  43204. __decorate([
  43205. BABYLON.serialize(),
  43206. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43207. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  43208. __decorate([
  43209. BABYLON.serializeAsTexture(),
  43210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43211. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  43212. __decorate([
  43213. BABYLON.serialize(),
  43214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43215. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  43216. __decorate([
  43217. BABYLON.serialize(),
  43218. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43219. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  43220. __decorate([
  43221. BABYLON.serialize(),
  43222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43223. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  43224. __decorate([
  43225. BABYLON.serialize(),
  43226. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43227. ], PBRMaterial.prototype, "unlit", void 0);
  43228. return PBRMaterial;
  43229. }(BABYLON.PBRBaseMaterial));
  43230. BABYLON.PBRMaterial = PBRMaterial;
  43231. })(BABYLON || (BABYLON = {}));
  43232. //# sourceMappingURL=babylon.pbrMaterial.js.map
  43233. "use strict";
  43234. var BABYLON;
  43235. (function (BABYLON) {
  43236. /**
  43237. * The PBR material of BJS following the metal roughness convention.
  43238. *
  43239. * This fits to the PBR convention in the GLTF definition:
  43240. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  43241. */
  43242. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  43243. __extends(PBRMetallicRoughnessMaterial, _super);
  43244. /**
  43245. * Instantiates a new PBRMetalRoughnessMaterial instance.
  43246. *
  43247. * @param name The material name
  43248. * @param scene The scene the material will be use in.
  43249. */
  43250. function PBRMetallicRoughnessMaterial(name, scene) {
  43251. var _this = _super.call(this, name, scene) || this;
  43252. _this._useRoughnessFromMetallicTextureAlpha = false;
  43253. _this._useRoughnessFromMetallicTextureGreen = true;
  43254. _this._useMetallnessFromMetallicTextureBlue = true;
  43255. _this.metallic = 1.0;
  43256. _this.roughness = 1.0;
  43257. return _this;
  43258. }
  43259. /**
  43260. * Return the currrent class name of the material.
  43261. */
  43262. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  43263. return "PBRMetallicRoughnessMaterial";
  43264. };
  43265. /**
  43266. * Return the active textures of the material.
  43267. */
  43268. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  43269. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43270. if (this.baseTexture) {
  43271. activeTextures.push(this.baseTexture);
  43272. }
  43273. if (this.metallicRoughnessTexture) {
  43274. activeTextures.push(this.metallicRoughnessTexture);
  43275. }
  43276. return activeTextures;
  43277. };
  43278. /**
  43279. * Checks to see if a texture is used in the material.
  43280. * @param texture - Base texture to use.
  43281. * @returns - Boolean specifying if a texture is used in the material.
  43282. */
  43283. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  43284. if (_super.prototype.hasTexture.call(this, texture)) {
  43285. return true;
  43286. }
  43287. if (this.baseTexture === texture) {
  43288. return true;
  43289. }
  43290. if (this.metallicRoughnessTexture === texture) {
  43291. return true;
  43292. }
  43293. return false;
  43294. };
  43295. /**
  43296. * Makes a duplicate of the current material.
  43297. * @param name - name to use for the new material.
  43298. */
  43299. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  43300. var _this = this;
  43301. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  43302. clone.id = name;
  43303. clone.name = name;
  43304. return clone;
  43305. };
  43306. /**
  43307. * Serialize the material to a parsable JSON object.
  43308. */
  43309. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  43310. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43311. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  43312. return serializationObject;
  43313. };
  43314. /**
  43315. * Parses a JSON object correponding to the serialize function.
  43316. */
  43317. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  43318. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  43319. };
  43320. __decorate([
  43321. BABYLON.serializeAsColor3(),
  43322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43323. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  43324. __decorate([
  43325. BABYLON.serializeAsTexture(),
  43326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43327. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  43328. __decorate([
  43329. BABYLON.serialize(),
  43330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43331. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  43332. __decorate([
  43333. BABYLON.serialize(),
  43334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43335. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  43336. __decorate([
  43337. BABYLON.serializeAsTexture(),
  43338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  43339. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  43340. return PBRMetallicRoughnessMaterial;
  43341. }(BABYLON.PBRBaseSimpleMaterial));
  43342. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  43343. })(BABYLON || (BABYLON = {}));
  43344. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  43345. "use strict";
  43346. var BABYLON;
  43347. (function (BABYLON) {
  43348. /**
  43349. * The PBR material of BJS following the specular glossiness convention.
  43350. *
  43351. * This fits to the PBR convention in the GLTF definition:
  43352. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  43353. */
  43354. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  43355. __extends(PBRSpecularGlossinessMaterial, _super);
  43356. /**
  43357. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  43358. *
  43359. * @param name The material name
  43360. * @param scene The scene the material will be use in.
  43361. */
  43362. function PBRSpecularGlossinessMaterial(name, scene) {
  43363. var _this = _super.call(this, name, scene) || this;
  43364. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  43365. return _this;
  43366. }
  43367. /**
  43368. * Return the currrent class name of the material.
  43369. */
  43370. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  43371. return "PBRSpecularGlossinessMaterial";
  43372. };
  43373. /**
  43374. * Return the active textures of the material.
  43375. */
  43376. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  43377. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43378. if (this.diffuseTexture) {
  43379. activeTextures.push(this.diffuseTexture);
  43380. }
  43381. if (this.specularGlossinessTexture) {
  43382. activeTextures.push(this.specularGlossinessTexture);
  43383. }
  43384. return activeTextures;
  43385. };
  43386. /**
  43387. * Checks to see if a texture is used in the material.
  43388. * @param texture - Base texture to use.
  43389. * @returns - Boolean specifying if a texture is used in the material.
  43390. */
  43391. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  43392. if (_super.prototype.hasTexture.call(this, texture)) {
  43393. return true;
  43394. }
  43395. if (this.diffuseTexture === texture) {
  43396. return true;
  43397. }
  43398. if (this.specularGlossinessTexture === texture) {
  43399. return true;
  43400. }
  43401. return false;
  43402. };
  43403. /**
  43404. * Makes a duplicate of the current material.
  43405. * @param name - name to use for the new material.
  43406. */
  43407. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  43408. var _this = this;
  43409. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  43410. clone.id = name;
  43411. clone.name = name;
  43412. return clone;
  43413. };
  43414. /**
  43415. * Serialize the material to a parsable JSON object.
  43416. */
  43417. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  43418. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43419. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  43420. return serializationObject;
  43421. };
  43422. /**
  43423. * Parses a JSON object correponding to the serialize function.
  43424. */
  43425. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43426. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43427. };
  43428. __decorate([
  43429. BABYLON.serializeAsColor3("diffuse"),
  43430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43431. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43432. __decorate([
  43433. BABYLON.serializeAsTexture(),
  43434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43435. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43436. __decorate([
  43437. BABYLON.serializeAsColor3("specular"),
  43438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43439. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43440. __decorate([
  43441. BABYLON.serialize(),
  43442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43443. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43444. __decorate([
  43445. BABYLON.serializeAsTexture(),
  43446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43447. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43448. return PBRSpecularGlossinessMaterial;
  43449. }(BABYLON.PBRBaseSimpleMaterial));
  43450. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43451. })(BABYLON || (BABYLON = {}));
  43452. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43453. "use strict";
  43454. var BABYLON;
  43455. (function (BABYLON) {
  43456. BABYLON.CameraInputTypes = {};
  43457. var CameraInputsManager = /** @class */ (function () {
  43458. function CameraInputsManager(camera) {
  43459. this.attached = {};
  43460. this.camera = camera;
  43461. this.checkInputs = function () { };
  43462. }
  43463. /**
  43464. * Add an input method to a camera.
  43465. * builtin inputs example: camera.inputs.addGamepad();
  43466. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43467. * @param input camera input method
  43468. */
  43469. CameraInputsManager.prototype.add = function (input) {
  43470. var type = input.getSimpleName();
  43471. if (this.attached[type]) {
  43472. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43473. return;
  43474. }
  43475. this.attached[type] = input;
  43476. input.camera = this.camera;
  43477. //for checkInputs, we are dynamically creating a function
  43478. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43479. if (input.checkInputs) {
  43480. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43481. }
  43482. if (this.attachedElement) {
  43483. input.attachControl(this.attachedElement);
  43484. }
  43485. };
  43486. /**
  43487. * Remove a specific input method from a camera
  43488. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43489. * @param inputToRemove camera input method
  43490. */
  43491. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43492. for (var cam in this.attached) {
  43493. var input = this.attached[cam];
  43494. if (input === inputToRemove) {
  43495. input.detachControl(this.attachedElement);
  43496. input.camera = null;
  43497. delete this.attached[cam];
  43498. this.rebuildInputCheck();
  43499. }
  43500. }
  43501. };
  43502. CameraInputsManager.prototype.removeByType = function (inputType) {
  43503. for (var cam in this.attached) {
  43504. var input = this.attached[cam];
  43505. if (input.getClassName() === inputType) {
  43506. input.detachControl(this.attachedElement);
  43507. input.camera = null;
  43508. delete this.attached[cam];
  43509. this.rebuildInputCheck();
  43510. }
  43511. }
  43512. };
  43513. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43514. var current = this.checkInputs;
  43515. return function () {
  43516. current();
  43517. fn();
  43518. };
  43519. };
  43520. CameraInputsManager.prototype.attachInput = function (input) {
  43521. if (this.attachedElement) {
  43522. input.attachControl(this.attachedElement, this.noPreventDefault);
  43523. }
  43524. };
  43525. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43526. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43527. if (this.attachedElement) {
  43528. return;
  43529. }
  43530. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43531. this.attachedElement = element;
  43532. this.noPreventDefault = noPreventDefault;
  43533. for (var cam in this.attached) {
  43534. this.attached[cam].attachControl(element, noPreventDefault);
  43535. }
  43536. };
  43537. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43538. if (disconnect === void 0) { disconnect = false; }
  43539. if (this.attachedElement !== element) {
  43540. return;
  43541. }
  43542. for (var cam in this.attached) {
  43543. this.attached[cam].detachControl(element);
  43544. if (disconnect) {
  43545. this.attached[cam].camera = null;
  43546. }
  43547. }
  43548. this.attachedElement = null;
  43549. };
  43550. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43551. this.checkInputs = function () { };
  43552. for (var cam in this.attached) {
  43553. var input = this.attached[cam];
  43554. if (input.checkInputs) {
  43555. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43556. }
  43557. }
  43558. };
  43559. /**
  43560. * Remove all attached input methods from a camera
  43561. */
  43562. CameraInputsManager.prototype.clear = function () {
  43563. if (this.attachedElement) {
  43564. this.detachElement(this.attachedElement, true);
  43565. }
  43566. this.attached = {};
  43567. this.attachedElement = null;
  43568. this.checkInputs = function () { };
  43569. };
  43570. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43571. var inputs = {};
  43572. for (var cam in this.attached) {
  43573. var input = this.attached[cam];
  43574. var res = BABYLON.SerializationHelper.Serialize(input);
  43575. inputs[input.getClassName()] = res;
  43576. }
  43577. serializedCamera.inputsmgr = inputs;
  43578. };
  43579. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43580. var parsedInputs = parsedCamera.inputsmgr;
  43581. if (parsedInputs) {
  43582. this.clear();
  43583. for (var n in parsedInputs) {
  43584. var construct = BABYLON.CameraInputTypes[n];
  43585. if (construct) {
  43586. var parsedinput = parsedInputs[n];
  43587. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43588. this.add(input);
  43589. }
  43590. }
  43591. }
  43592. else {
  43593. //2016-03-08 this part is for managing backward compatibility
  43594. for (var n in this.attached) {
  43595. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43596. if (construct) {
  43597. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43598. this.remove(this.attached[n]);
  43599. this.add(input);
  43600. }
  43601. }
  43602. }
  43603. };
  43604. return CameraInputsManager;
  43605. }());
  43606. BABYLON.CameraInputsManager = CameraInputsManager;
  43607. })(BABYLON || (BABYLON = {}));
  43608. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43609. "use strict";
  43610. var BABYLON;
  43611. (function (BABYLON) {
  43612. var TargetCamera = /** @class */ (function (_super) {
  43613. __extends(TargetCamera, _super);
  43614. function TargetCamera(name, position, scene) {
  43615. var _this = _super.call(this, name, position, scene) || this;
  43616. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43617. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43618. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43619. _this.speed = 2.0;
  43620. _this.noRotationConstraint = false;
  43621. _this.lockedTarget = null;
  43622. _this._currentTarget = BABYLON.Vector3.Zero();
  43623. _this._viewMatrix = BABYLON.Matrix.Zero();
  43624. _this._camMatrix = BABYLON.Matrix.Zero();
  43625. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43626. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43627. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43628. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43629. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43630. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43631. _this._tempMatrix = BABYLON.Matrix.Zero();
  43632. return _this;
  43633. }
  43634. TargetCamera.prototype.getFrontPosition = function (distance) {
  43635. this.getWorldMatrix();
  43636. var direction = this.getTarget().subtract(this.position);
  43637. direction.normalize();
  43638. direction.scaleInPlace(distance);
  43639. return this.globalPosition.add(direction);
  43640. };
  43641. TargetCamera.prototype._getLockedTargetPosition = function () {
  43642. if (!this.lockedTarget) {
  43643. return null;
  43644. }
  43645. if (this.lockedTarget.absolutePosition) {
  43646. this.lockedTarget.computeWorldMatrix();
  43647. }
  43648. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43649. };
  43650. TargetCamera.prototype.storeState = function () {
  43651. this._storedPosition = this.position.clone();
  43652. this._storedRotation = this.rotation.clone();
  43653. if (this.rotationQuaternion) {
  43654. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43655. }
  43656. return _super.prototype.storeState.call(this);
  43657. };
  43658. /**
  43659. * Restored camera state. You must call storeState() first
  43660. */
  43661. TargetCamera.prototype._restoreStateValues = function () {
  43662. if (!_super.prototype._restoreStateValues.call(this)) {
  43663. return false;
  43664. }
  43665. this.position = this._storedPosition.clone();
  43666. this.rotation = this._storedRotation.clone();
  43667. if (this.rotationQuaternion) {
  43668. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43669. }
  43670. this.cameraDirection.copyFromFloats(0, 0, 0);
  43671. this.cameraRotation.copyFromFloats(0, 0);
  43672. return true;
  43673. };
  43674. // Cache
  43675. TargetCamera.prototype._initCache = function () {
  43676. _super.prototype._initCache.call(this);
  43677. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43678. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43679. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43680. };
  43681. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43682. if (!ignoreParentClass) {
  43683. _super.prototype._updateCache.call(this);
  43684. }
  43685. var lockedTargetPosition = this._getLockedTargetPosition();
  43686. if (!lockedTargetPosition) {
  43687. this._cache.lockedTarget = null;
  43688. }
  43689. else {
  43690. if (!this._cache.lockedTarget) {
  43691. this._cache.lockedTarget = lockedTargetPosition.clone();
  43692. }
  43693. else {
  43694. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43695. }
  43696. }
  43697. this._cache.rotation.copyFrom(this.rotation);
  43698. if (this.rotationQuaternion)
  43699. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43700. };
  43701. // Synchronized
  43702. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43703. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43704. return false;
  43705. }
  43706. var lockedTargetPosition = this._getLockedTargetPosition();
  43707. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43708. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43709. };
  43710. // Methods
  43711. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43712. var engine = this.getEngine();
  43713. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43714. };
  43715. // Target
  43716. TargetCamera.prototype.setTarget = function (target) {
  43717. this.upVector.normalize();
  43718. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43719. this._camMatrix.invert();
  43720. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43721. var vDir = target.subtract(this.position);
  43722. if (vDir.x >= 0.0) {
  43723. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43724. }
  43725. else {
  43726. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43727. }
  43728. this.rotation.z = 0;
  43729. if (isNaN(this.rotation.x)) {
  43730. this.rotation.x = 0;
  43731. }
  43732. if (isNaN(this.rotation.y)) {
  43733. this.rotation.y = 0;
  43734. }
  43735. if (isNaN(this.rotation.z)) {
  43736. this.rotation.z = 0;
  43737. }
  43738. if (this.rotationQuaternion) {
  43739. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43740. }
  43741. };
  43742. /**
  43743. * Return the current target position of the camera. This value is expressed in local space.
  43744. */
  43745. TargetCamera.prototype.getTarget = function () {
  43746. return this._currentTarget;
  43747. };
  43748. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43749. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43750. };
  43751. TargetCamera.prototype._updatePosition = function () {
  43752. if (this.parent) {
  43753. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43754. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43755. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43756. return;
  43757. }
  43758. this.position.addInPlace(this.cameraDirection);
  43759. };
  43760. TargetCamera.prototype._checkInputs = function () {
  43761. var needToMove = this._decideIfNeedsToMove();
  43762. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43763. // Move
  43764. if (needToMove) {
  43765. this._updatePosition();
  43766. }
  43767. // Rotate
  43768. if (needToRotate) {
  43769. this.rotation.x += this.cameraRotation.x;
  43770. this.rotation.y += this.cameraRotation.y;
  43771. //rotate, if quaternion is set and rotation was used
  43772. if (this.rotationQuaternion) {
  43773. var len = this.rotation.lengthSquared();
  43774. if (len) {
  43775. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43776. }
  43777. }
  43778. if (!this.noRotationConstraint) {
  43779. var limit = (Math.PI / 2) * 0.95;
  43780. if (this.rotation.x > limit)
  43781. this.rotation.x = limit;
  43782. if (this.rotation.x < -limit)
  43783. this.rotation.x = -limit;
  43784. }
  43785. }
  43786. // Inertia
  43787. if (needToMove) {
  43788. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43789. this.cameraDirection.x = 0;
  43790. }
  43791. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43792. this.cameraDirection.y = 0;
  43793. }
  43794. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43795. this.cameraDirection.z = 0;
  43796. }
  43797. this.cameraDirection.scaleInPlace(this.inertia);
  43798. }
  43799. if (needToRotate) {
  43800. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43801. this.cameraRotation.x = 0;
  43802. }
  43803. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43804. this.cameraRotation.y = 0;
  43805. }
  43806. this.cameraRotation.scaleInPlace(this.inertia);
  43807. }
  43808. _super.prototype._checkInputs.call(this);
  43809. };
  43810. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43811. if (this.rotationQuaternion) {
  43812. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43813. }
  43814. else {
  43815. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43816. }
  43817. //update the up vector!
  43818. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43819. };
  43820. TargetCamera.prototype._getViewMatrix = function () {
  43821. if (this.lockedTarget) {
  43822. this.setTarget(this._getLockedTargetPosition());
  43823. }
  43824. // Compute
  43825. this._updateCameraRotationMatrix();
  43826. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43827. // Computing target and final matrix
  43828. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43829. if (this.getScene().useRightHandedSystem) {
  43830. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43831. }
  43832. else {
  43833. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43834. }
  43835. return this._viewMatrix;
  43836. };
  43837. /**
  43838. * @override
  43839. * Override Camera.createRigCamera
  43840. */
  43841. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43842. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43843. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43844. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43845. if (!this.rotationQuaternion) {
  43846. this.rotationQuaternion = new BABYLON.Quaternion();
  43847. }
  43848. rigCamera._cameraRigParams = {};
  43849. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43850. }
  43851. return rigCamera;
  43852. }
  43853. return null;
  43854. };
  43855. /**
  43856. * @override
  43857. * Override Camera._updateRigCameras
  43858. */
  43859. TargetCamera.prototype._updateRigCameras = function () {
  43860. var camLeft = this._rigCameras[0];
  43861. var camRight = this._rigCameras[1];
  43862. switch (this.cameraRigMode) {
  43863. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43864. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43865. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43866. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43867. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43868. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43869. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43870. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43871. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43872. camLeft.setTarget(this.getTarget());
  43873. camRight.setTarget(this.getTarget());
  43874. break;
  43875. case BABYLON.Camera.RIG_MODE_VR:
  43876. if (camLeft.rotationQuaternion) {
  43877. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43878. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43879. }
  43880. else {
  43881. camLeft.rotation.copyFrom(this.rotation);
  43882. camRight.rotation.copyFrom(this.rotation);
  43883. }
  43884. camLeft.position.copyFrom(this.position);
  43885. camRight.position.copyFrom(this.position);
  43886. break;
  43887. }
  43888. _super.prototype._updateRigCameras.call(this);
  43889. };
  43890. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43891. if (!this._rigCamTransformMatrix) {
  43892. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43893. }
  43894. var target = this.getTarget();
  43895. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43896. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43897. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43898. };
  43899. TargetCamera.prototype.getClassName = function () {
  43900. return "TargetCamera";
  43901. };
  43902. __decorate([
  43903. BABYLON.serializeAsVector3()
  43904. ], TargetCamera.prototype, "rotation", void 0);
  43905. __decorate([
  43906. BABYLON.serialize()
  43907. ], TargetCamera.prototype, "speed", void 0);
  43908. __decorate([
  43909. BABYLON.serializeAsMeshReference("lockedTargetId")
  43910. ], TargetCamera.prototype, "lockedTarget", void 0);
  43911. return TargetCamera;
  43912. }(BABYLON.Camera));
  43913. BABYLON.TargetCamera = TargetCamera;
  43914. })(BABYLON || (BABYLON = {}));
  43915. //# sourceMappingURL=babylon.targetCamera.js.map
  43916. "use strict";
  43917. var BABYLON;
  43918. (function (BABYLON) {
  43919. var FreeCameraMouseInput = /** @class */ (function () {
  43920. function FreeCameraMouseInput(touchEnabled) {
  43921. if (touchEnabled === void 0) { touchEnabled = true; }
  43922. this.touchEnabled = touchEnabled;
  43923. this.buttons = [0, 1, 2];
  43924. this.angularSensibility = 2000.0;
  43925. this.previousPosition = null;
  43926. }
  43927. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43928. var _this = this;
  43929. var engine = this.camera.getEngine();
  43930. if (!this._pointerInput) {
  43931. this._pointerInput = function (p, s) {
  43932. var evt = p.event;
  43933. if (engine.isInVRExclusivePointerMode) {
  43934. return;
  43935. }
  43936. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43937. return;
  43938. }
  43939. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43940. return;
  43941. }
  43942. var srcElement = (evt.srcElement || evt.target);
  43943. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43944. try {
  43945. srcElement.setPointerCapture(evt.pointerId);
  43946. }
  43947. catch (e) {
  43948. //Nothing to do with the error. Execution will continue.
  43949. }
  43950. _this.previousPosition = {
  43951. x: evt.clientX,
  43952. y: evt.clientY
  43953. };
  43954. if (!noPreventDefault) {
  43955. evt.preventDefault();
  43956. element.focus();
  43957. }
  43958. }
  43959. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43960. try {
  43961. srcElement.releasePointerCapture(evt.pointerId);
  43962. }
  43963. catch (e) {
  43964. //Nothing to do with the error.
  43965. }
  43966. _this.previousPosition = null;
  43967. if (!noPreventDefault) {
  43968. evt.preventDefault();
  43969. }
  43970. }
  43971. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43972. if (!_this.previousPosition || engine.isPointerLock) {
  43973. return;
  43974. }
  43975. var offsetX = evt.clientX - _this.previousPosition.x;
  43976. var offsetY = evt.clientY - _this.previousPosition.y;
  43977. if (_this.camera.getScene().useRightHandedSystem) {
  43978. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43979. }
  43980. else {
  43981. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43982. }
  43983. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43984. _this.previousPosition = {
  43985. x: evt.clientX,
  43986. y: evt.clientY
  43987. };
  43988. if (!noPreventDefault) {
  43989. evt.preventDefault();
  43990. }
  43991. }
  43992. };
  43993. }
  43994. this._onMouseMove = function (evt) {
  43995. if (!engine.isPointerLock) {
  43996. return;
  43997. }
  43998. if (engine.isInVRExclusivePointerMode) {
  43999. return;
  44000. }
  44001. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44002. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44003. if (_this.camera.getScene().useRightHandedSystem) {
  44004. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  44005. }
  44006. else {
  44007. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  44008. }
  44009. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  44010. _this.previousPosition = null;
  44011. if (!noPreventDefault) {
  44012. evt.preventDefault();
  44013. }
  44014. };
  44015. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  44016. element.addEventListener("mousemove", this._onMouseMove, false);
  44017. };
  44018. FreeCameraMouseInput.prototype.detachControl = function (element) {
  44019. if (this._observer && element) {
  44020. this.camera.getScene().onPointerObservable.remove(this._observer);
  44021. if (this._onMouseMove) {
  44022. element.removeEventListener("mousemove", this._onMouseMove);
  44023. }
  44024. this._observer = null;
  44025. this._onMouseMove = null;
  44026. this.previousPosition = null;
  44027. }
  44028. };
  44029. FreeCameraMouseInput.prototype.getClassName = function () {
  44030. return "FreeCameraMouseInput";
  44031. };
  44032. FreeCameraMouseInput.prototype.getSimpleName = function () {
  44033. return "mouse";
  44034. };
  44035. __decorate([
  44036. BABYLON.serialize()
  44037. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  44038. __decorate([
  44039. BABYLON.serialize()
  44040. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  44041. return FreeCameraMouseInput;
  44042. }());
  44043. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  44044. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  44045. })(BABYLON || (BABYLON = {}));
  44046. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  44047. "use strict";
  44048. var BABYLON;
  44049. (function (BABYLON) {
  44050. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  44051. function FreeCameraKeyboardMoveInput() {
  44052. this._keys = new Array();
  44053. this.keysUp = [38];
  44054. this.keysDown = [40];
  44055. this.keysLeft = [37];
  44056. this.keysRight = [39];
  44057. }
  44058. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44059. var _this = this;
  44060. if (this._onCanvasBlurObserver) {
  44061. return;
  44062. }
  44063. this._scene = this.camera.getScene();
  44064. this._engine = this._scene.getEngine();
  44065. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44066. _this._keys = [];
  44067. });
  44068. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44069. var evt = info.event;
  44070. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44071. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44072. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44073. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44074. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44075. var index = _this._keys.indexOf(evt.keyCode);
  44076. if (index === -1) {
  44077. _this._keys.push(evt.keyCode);
  44078. }
  44079. if (!noPreventDefault) {
  44080. evt.preventDefault();
  44081. }
  44082. }
  44083. }
  44084. else {
  44085. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44086. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44087. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44088. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44089. var index = _this._keys.indexOf(evt.keyCode);
  44090. if (index >= 0) {
  44091. _this._keys.splice(index, 1);
  44092. }
  44093. if (!noPreventDefault) {
  44094. evt.preventDefault();
  44095. }
  44096. }
  44097. }
  44098. });
  44099. };
  44100. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44101. if (this._scene) {
  44102. if (this._onKeyboardObserver) {
  44103. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44104. }
  44105. if (this._onCanvasBlurObserver) {
  44106. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44107. }
  44108. this._onKeyboardObserver = null;
  44109. this._onCanvasBlurObserver = null;
  44110. }
  44111. this._keys = [];
  44112. };
  44113. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44114. if (this._onKeyboardObserver) {
  44115. var camera = this.camera;
  44116. // Keyboard
  44117. for (var index = 0; index < this._keys.length; index++) {
  44118. var keyCode = this._keys[index];
  44119. var speed = camera._computeLocalCameraSpeed();
  44120. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44121. camera._localDirection.copyFromFloats(-speed, 0, 0);
  44122. }
  44123. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44124. camera._localDirection.copyFromFloats(0, 0, speed);
  44125. }
  44126. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44127. camera._localDirection.copyFromFloats(speed, 0, 0);
  44128. }
  44129. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44130. camera._localDirection.copyFromFloats(0, 0, -speed);
  44131. }
  44132. if (camera.getScene().useRightHandedSystem) {
  44133. camera._localDirection.z *= -1;
  44134. }
  44135. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  44136. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  44137. camera.cameraDirection.addInPlace(camera._transformedDirection);
  44138. }
  44139. }
  44140. };
  44141. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  44142. return "FreeCameraKeyboardMoveInput";
  44143. };
  44144. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  44145. this._keys = [];
  44146. };
  44147. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44148. return "keyboard";
  44149. };
  44150. __decorate([
  44151. BABYLON.serialize()
  44152. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44153. __decorate([
  44154. BABYLON.serialize()
  44155. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44156. __decorate([
  44157. BABYLON.serialize()
  44158. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44159. __decorate([
  44160. BABYLON.serialize()
  44161. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44162. return FreeCameraKeyboardMoveInput;
  44163. }());
  44164. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  44165. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  44166. })(BABYLON || (BABYLON = {}));
  44167. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  44168. "use strict";
  44169. var BABYLON;
  44170. (function (BABYLON) {
  44171. var FreeCameraInputsManager = /** @class */ (function (_super) {
  44172. __extends(FreeCameraInputsManager, _super);
  44173. function FreeCameraInputsManager(camera) {
  44174. return _super.call(this, camera) || this;
  44175. }
  44176. FreeCameraInputsManager.prototype.addKeyboard = function () {
  44177. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  44178. return this;
  44179. };
  44180. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  44181. if (touchEnabled === void 0) { touchEnabled = true; }
  44182. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  44183. return this;
  44184. };
  44185. FreeCameraInputsManager.prototype.addGamepad = function () {
  44186. this.add(new BABYLON.FreeCameraGamepadInput());
  44187. return this;
  44188. };
  44189. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  44190. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  44191. return this;
  44192. };
  44193. FreeCameraInputsManager.prototype.addTouch = function () {
  44194. this.add(new BABYLON.FreeCameraTouchInput());
  44195. return this;
  44196. };
  44197. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  44198. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  44199. return this;
  44200. };
  44201. return FreeCameraInputsManager;
  44202. }(BABYLON.CameraInputsManager));
  44203. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  44204. })(BABYLON || (BABYLON = {}));
  44205. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  44206. "use strict";
  44207. var BABYLON;
  44208. (function (BABYLON) {
  44209. var FreeCamera = /** @class */ (function (_super) {
  44210. __extends(FreeCamera, _super);
  44211. function FreeCamera(name, position, scene) {
  44212. var _this = _super.call(this, name, position, scene) || this;
  44213. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  44214. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  44215. _this.checkCollisions = false;
  44216. _this.applyGravity = false;
  44217. _this._needMoveForGravity = false;
  44218. _this._oldPosition = BABYLON.Vector3.Zero();
  44219. _this._diffPosition = BABYLON.Vector3.Zero();
  44220. _this._newPosition = BABYLON.Vector3.Zero();
  44221. // Collisions
  44222. _this._collisionMask = -1;
  44223. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44224. if (collidedMesh === void 0) { collidedMesh = null; }
  44225. //TODO move this to the collision coordinator!
  44226. if (_this.getScene().workerCollisions)
  44227. newPosition.multiplyInPlace(_this._collider._radius);
  44228. var updatePosition = function (newPos) {
  44229. _this._newPosition.copyFrom(newPos);
  44230. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  44231. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  44232. _this.position.addInPlace(_this._diffPosition);
  44233. if (_this.onCollide && collidedMesh) {
  44234. _this.onCollide(collidedMesh);
  44235. }
  44236. }
  44237. };
  44238. updatePosition(newPosition);
  44239. };
  44240. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  44241. _this.inputs.addKeyboard().addMouse();
  44242. return _this;
  44243. }
  44244. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  44245. //-- begin properties for backward compatibility for inputs
  44246. /**
  44247. * Gets the input sensibility for a mouse input. (default is 2000.0)
  44248. * Higher values reduce sensitivity.
  44249. */
  44250. get: function () {
  44251. var mouse = this.inputs.attached["mouse"];
  44252. if (mouse)
  44253. return mouse.angularSensibility;
  44254. return 0;
  44255. },
  44256. /**
  44257. * Sets the input sensibility for a mouse input. (default is 2000.0)
  44258. * Higher values reduce sensitivity.
  44259. */
  44260. set: function (value) {
  44261. var mouse = this.inputs.attached["mouse"];
  44262. if (mouse)
  44263. mouse.angularSensibility = value;
  44264. },
  44265. enumerable: true,
  44266. configurable: true
  44267. });
  44268. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  44269. get: function () {
  44270. var keyboard = this.inputs.attached["keyboard"];
  44271. if (keyboard)
  44272. return keyboard.keysUp;
  44273. return [];
  44274. },
  44275. set: function (value) {
  44276. var keyboard = this.inputs.attached["keyboard"];
  44277. if (keyboard)
  44278. keyboard.keysUp = value;
  44279. },
  44280. enumerable: true,
  44281. configurable: true
  44282. });
  44283. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  44284. get: function () {
  44285. var keyboard = this.inputs.attached["keyboard"];
  44286. if (keyboard)
  44287. return keyboard.keysDown;
  44288. return [];
  44289. },
  44290. set: function (value) {
  44291. var keyboard = this.inputs.attached["keyboard"];
  44292. if (keyboard)
  44293. keyboard.keysDown = value;
  44294. },
  44295. enumerable: true,
  44296. configurable: true
  44297. });
  44298. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  44299. get: function () {
  44300. var keyboard = this.inputs.attached["keyboard"];
  44301. if (keyboard)
  44302. return keyboard.keysLeft;
  44303. return [];
  44304. },
  44305. set: function (value) {
  44306. var keyboard = this.inputs.attached["keyboard"];
  44307. if (keyboard)
  44308. keyboard.keysLeft = value;
  44309. },
  44310. enumerable: true,
  44311. configurable: true
  44312. });
  44313. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  44314. get: function () {
  44315. var keyboard = this.inputs.attached["keyboard"];
  44316. if (keyboard)
  44317. return keyboard.keysRight;
  44318. return [];
  44319. },
  44320. set: function (value) {
  44321. var keyboard = this.inputs.attached["keyboard"];
  44322. if (keyboard)
  44323. keyboard.keysRight = value;
  44324. },
  44325. enumerable: true,
  44326. configurable: true
  44327. });
  44328. // Controls
  44329. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44330. this.inputs.attachElement(element, noPreventDefault);
  44331. };
  44332. FreeCamera.prototype.detachControl = function (element) {
  44333. this.inputs.detachElement(element);
  44334. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  44335. this.cameraRotation = new BABYLON.Vector2(0, 0);
  44336. };
  44337. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  44338. get: function () {
  44339. return this._collisionMask;
  44340. },
  44341. set: function (mask) {
  44342. this._collisionMask = !isNaN(mask) ? mask : -1;
  44343. },
  44344. enumerable: true,
  44345. configurable: true
  44346. });
  44347. FreeCamera.prototype._collideWithWorld = function (displacement) {
  44348. var globalPosition;
  44349. if (this.parent) {
  44350. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  44351. }
  44352. else {
  44353. globalPosition = this.position;
  44354. }
  44355. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  44356. this._oldPosition.addInPlace(this.ellipsoidOffset);
  44357. if (!this._collider) {
  44358. this._collider = new BABYLON.Collider();
  44359. }
  44360. this._collider._radius = this.ellipsoid;
  44361. this._collider.collisionMask = this._collisionMask;
  44362. //no need for clone, as long as gravity is not on.
  44363. var actualDisplacement = displacement;
  44364. //add gravity to the direction to prevent the dual-collision checking
  44365. if (this.applyGravity) {
  44366. //this prevents mending with cameraDirection, a global variable of the free camera class.
  44367. actualDisplacement = displacement.add(this.getScene().gravity);
  44368. }
  44369. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44370. };
  44371. FreeCamera.prototype._checkInputs = function () {
  44372. if (!this._localDirection) {
  44373. this._localDirection = BABYLON.Vector3.Zero();
  44374. this._transformedDirection = BABYLON.Vector3.Zero();
  44375. }
  44376. this.inputs.checkInputs();
  44377. _super.prototype._checkInputs.call(this);
  44378. };
  44379. FreeCamera.prototype._decideIfNeedsToMove = function () {
  44380. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  44381. };
  44382. FreeCamera.prototype._updatePosition = function () {
  44383. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  44384. this._collideWithWorld(this.cameraDirection);
  44385. }
  44386. else {
  44387. _super.prototype._updatePosition.call(this);
  44388. }
  44389. };
  44390. FreeCamera.prototype.dispose = function () {
  44391. this.inputs.clear();
  44392. _super.prototype.dispose.call(this);
  44393. };
  44394. FreeCamera.prototype.getClassName = function () {
  44395. return "FreeCamera";
  44396. };
  44397. __decorate([
  44398. BABYLON.serializeAsVector3()
  44399. ], FreeCamera.prototype, "ellipsoid", void 0);
  44400. __decorate([
  44401. BABYLON.serializeAsVector3()
  44402. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  44403. __decorate([
  44404. BABYLON.serialize()
  44405. ], FreeCamera.prototype, "checkCollisions", void 0);
  44406. __decorate([
  44407. BABYLON.serialize()
  44408. ], FreeCamera.prototype, "applyGravity", void 0);
  44409. return FreeCamera;
  44410. }(BABYLON.TargetCamera));
  44411. BABYLON.FreeCamera = FreeCamera;
  44412. })(BABYLON || (BABYLON = {}));
  44413. //# sourceMappingURL=babylon.freeCamera.js.map
  44414. "use strict";
  44415. var BABYLON;
  44416. (function (BABYLON) {
  44417. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  44418. function ArcRotateCameraKeyboardMoveInput() {
  44419. this._keys = new Array();
  44420. this.keysUp = [38];
  44421. this.keysDown = [40];
  44422. this.keysLeft = [37];
  44423. this.keysRight = [39];
  44424. this.keysReset = [220];
  44425. this.panningSensibility = 50.0;
  44426. this.zoomingSensibility = 25.0;
  44427. this.useAltToZoom = true;
  44428. }
  44429. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44430. var _this = this;
  44431. if (this._onCanvasBlurObserver) {
  44432. return;
  44433. }
  44434. this._scene = this.camera.getScene();
  44435. this._engine = this._scene.getEngine();
  44436. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44437. _this._keys = [];
  44438. });
  44439. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44440. var evt = info.event;
  44441. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44442. _this._ctrlPressed = evt.ctrlKey;
  44443. _this._altPressed = evt.altKey;
  44444. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44445. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44446. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44447. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44448. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44449. var index = _this._keys.indexOf(evt.keyCode);
  44450. if (index === -1) {
  44451. _this._keys.push(evt.keyCode);
  44452. }
  44453. if (evt.preventDefault) {
  44454. if (!noPreventDefault) {
  44455. evt.preventDefault();
  44456. }
  44457. }
  44458. }
  44459. }
  44460. else {
  44461. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44462. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44463. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44464. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44465. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44466. var index = _this._keys.indexOf(evt.keyCode);
  44467. if (index >= 0) {
  44468. _this._keys.splice(index, 1);
  44469. }
  44470. if (evt.preventDefault) {
  44471. if (!noPreventDefault) {
  44472. evt.preventDefault();
  44473. }
  44474. }
  44475. }
  44476. }
  44477. });
  44478. };
  44479. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44480. if (this._scene) {
  44481. if (this._onKeyboardObserver) {
  44482. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44483. }
  44484. if (this._onCanvasBlurObserver) {
  44485. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44486. }
  44487. this._onKeyboardObserver = null;
  44488. this._onCanvasBlurObserver = null;
  44489. }
  44490. this._keys = [];
  44491. };
  44492. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44493. if (this._onKeyboardObserver) {
  44494. var camera = this.camera;
  44495. for (var index = 0; index < this._keys.length; index++) {
  44496. var keyCode = this._keys[index];
  44497. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44498. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44499. camera.inertialPanningX -= 1 / this.panningSensibility;
  44500. }
  44501. else {
  44502. camera.inertialAlphaOffset -= 0.01;
  44503. }
  44504. }
  44505. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44506. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44507. camera.inertialPanningY += 1 / this.panningSensibility;
  44508. }
  44509. else if (this._altPressed && this.useAltToZoom) {
  44510. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44511. }
  44512. else {
  44513. camera.inertialBetaOffset -= 0.01;
  44514. }
  44515. }
  44516. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44517. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44518. camera.inertialPanningX += 1 / this.panningSensibility;
  44519. }
  44520. else {
  44521. camera.inertialAlphaOffset += 0.01;
  44522. }
  44523. }
  44524. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44525. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44526. camera.inertialPanningY -= 1 / this.panningSensibility;
  44527. }
  44528. else if (this._altPressed && this.useAltToZoom) {
  44529. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44530. }
  44531. else {
  44532. camera.inertialBetaOffset += 0.01;
  44533. }
  44534. }
  44535. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44536. camera.restoreState();
  44537. }
  44538. }
  44539. }
  44540. };
  44541. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44542. return "ArcRotateCameraKeyboardMoveInput";
  44543. };
  44544. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44545. return "keyboard";
  44546. };
  44547. __decorate([
  44548. BABYLON.serialize()
  44549. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44550. __decorate([
  44551. BABYLON.serialize()
  44552. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44553. __decorate([
  44554. BABYLON.serialize()
  44555. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44556. __decorate([
  44557. BABYLON.serialize()
  44558. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44559. __decorate([
  44560. BABYLON.serialize()
  44561. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44562. __decorate([
  44563. BABYLON.serialize()
  44564. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44565. __decorate([
  44566. BABYLON.serialize()
  44567. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44568. __decorate([
  44569. BABYLON.serialize()
  44570. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44571. return ArcRotateCameraKeyboardMoveInput;
  44572. }());
  44573. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44574. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44575. })(BABYLON || (BABYLON = {}));
  44576. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44577. "use strict";
  44578. var BABYLON;
  44579. (function (BABYLON) {
  44580. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44581. function ArcRotateCameraMouseWheelInput() {
  44582. this.wheelPrecision = 3.0;
  44583. /**
  44584. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44585. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44586. */
  44587. this.wheelDeltaPercentage = 0;
  44588. }
  44589. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44590. var _this = this;
  44591. this._wheel = function (p, s) {
  44592. //sanity check - this should be a PointerWheel event.
  44593. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44594. return;
  44595. var event = p.event;
  44596. var delta = 0;
  44597. if (event.wheelDelta) {
  44598. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44599. }
  44600. else if (event.detail) {
  44601. delta = -event.detail / _this.wheelPrecision;
  44602. }
  44603. if (delta)
  44604. _this.camera.inertialRadiusOffset += delta;
  44605. if (event.preventDefault) {
  44606. if (!noPreventDefault) {
  44607. event.preventDefault();
  44608. }
  44609. }
  44610. };
  44611. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44612. };
  44613. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44614. if (this._observer && element) {
  44615. this.camera.getScene().onPointerObservable.remove(this._observer);
  44616. this._observer = null;
  44617. this._wheel = null;
  44618. }
  44619. };
  44620. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44621. return "ArcRotateCameraMouseWheelInput";
  44622. };
  44623. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44624. return "mousewheel";
  44625. };
  44626. __decorate([
  44627. BABYLON.serialize()
  44628. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44629. __decorate([
  44630. BABYLON.serialize()
  44631. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44632. return ArcRotateCameraMouseWheelInput;
  44633. }());
  44634. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44635. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44636. })(BABYLON || (BABYLON = {}));
  44637. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44638. "use strict";
  44639. var BABYLON;
  44640. (function (BABYLON) {
  44641. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44642. function ArcRotateCameraPointersInput() {
  44643. this.buttons = [0, 1, 2];
  44644. this.angularSensibilityX = 1000.0;
  44645. this.angularSensibilityY = 1000.0;
  44646. this.pinchPrecision = 12.0;
  44647. /**
  44648. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44649. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44650. */
  44651. this.pinchDeltaPercentage = 0;
  44652. this.panningSensibility = 1000.0;
  44653. this.multiTouchPanning = true;
  44654. this.multiTouchPanAndZoom = true;
  44655. this._isPanClick = false;
  44656. this.pinchInwards = true;
  44657. }
  44658. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44659. var _this = this;
  44660. var engine = this.camera.getEngine();
  44661. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44662. var pointA = null;
  44663. var pointB = null;
  44664. var previousPinchSquaredDistance = 0;
  44665. var initialDistance = 0;
  44666. var twoFingerActivityCount = 0;
  44667. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44668. this._pointerInput = function (p, s) {
  44669. var evt = p.event;
  44670. var isTouch = p.event.pointerType === "touch";
  44671. if (engine.isInVRExclusivePointerMode) {
  44672. return;
  44673. }
  44674. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44675. return;
  44676. }
  44677. var srcElement = (evt.srcElement || evt.target);
  44678. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44679. try {
  44680. srcElement.setPointerCapture(evt.pointerId);
  44681. }
  44682. catch (e) {
  44683. //Nothing to do with the error. Execution will continue.
  44684. }
  44685. // Manage panning with pan button click
  44686. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44687. // manage pointers
  44688. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44689. if (pointA === null) {
  44690. pointA = cacheSoloPointer;
  44691. }
  44692. else if (pointB === null) {
  44693. pointB = cacheSoloPointer;
  44694. }
  44695. if (!noPreventDefault) {
  44696. evt.preventDefault();
  44697. element.focus();
  44698. }
  44699. }
  44700. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44701. _this.camera.restoreState();
  44702. }
  44703. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44704. try {
  44705. srcElement.releasePointerCapture(evt.pointerId);
  44706. }
  44707. catch (e) {
  44708. //Nothing to do with the error.
  44709. }
  44710. cacheSoloPointer = null;
  44711. previousPinchSquaredDistance = 0;
  44712. previousMultiTouchPanPosition.isPaning = false;
  44713. previousMultiTouchPanPosition.isPinching = false;
  44714. twoFingerActivityCount = 0;
  44715. initialDistance = 0;
  44716. if (!isTouch) {
  44717. pointB = null; // Mouse and pen are mono pointer
  44718. }
  44719. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44720. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44721. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44722. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44723. if (engine.badOS) {
  44724. pointA = pointB = null;
  44725. }
  44726. else {
  44727. //only remove the impacted pointer in case of multitouch allowing on most
  44728. //platforms switching from rotate to zoom and pan seamlessly.
  44729. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44730. pointA = pointB;
  44731. pointB = null;
  44732. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44733. }
  44734. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44735. pointB = null;
  44736. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44737. }
  44738. else {
  44739. pointA = pointB = null;
  44740. }
  44741. }
  44742. if (!noPreventDefault) {
  44743. evt.preventDefault();
  44744. }
  44745. }
  44746. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44747. if (!noPreventDefault) {
  44748. evt.preventDefault();
  44749. }
  44750. // One button down
  44751. if (pointA && pointB === null && cacheSoloPointer) {
  44752. if (_this.panningSensibility !== 0 &&
  44753. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44754. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44755. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44756. }
  44757. else {
  44758. var offsetX = evt.clientX - cacheSoloPointer.x;
  44759. var offsetY = evt.clientY - cacheSoloPointer.y;
  44760. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44761. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44762. }
  44763. cacheSoloPointer.x = evt.clientX;
  44764. cacheSoloPointer.y = evt.clientY;
  44765. }
  44766. else if (pointA && pointB) {
  44767. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44768. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44769. ed.x = evt.clientX;
  44770. ed.y = evt.clientY;
  44771. var direction = _this.pinchInwards ? 1 : -1;
  44772. var distX = pointA.x - pointB.x;
  44773. var distY = pointA.y - pointB.y;
  44774. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44775. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44776. if (previousPinchSquaredDistance === 0) {
  44777. initialDistance = pinchDistance;
  44778. previousPinchSquaredDistance = pinchSquaredDistance;
  44779. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44780. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44781. return;
  44782. }
  44783. if (_this.multiTouchPanAndZoom) {
  44784. if (_this.pinchDeltaPercentage) {
  44785. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44786. }
  44787. else {
  44788. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44789. (_this.pinchPrecision *
  44790. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44791. direction);
  44792. }
  44793. if (_this.panningSensibility !== 0) {
  44794. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44795. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44796. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44797. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44798. previousMultiTouchPanPosition.x = pointersCenterX;
  44799. previousMultiTouchPanPosition.y = pointersCenterY;
  44800. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44801. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44802. }
  44803. }
  44804. else {
  44805. twoFingerActivityCount++;
  44806. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44807. if (_this.pinchDeltaPercentage) {
  44808. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44809. }
  44810. else {
  44811. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44812. (_this.pinchPrecision *
  44813. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44814. direction);
  44815. }
  44816. previousMultiTouchPanPosition.isPaning = false;
  44817. previousMultiTouchPanPosition.isPinching = true;
  44818. }
  44819. else {
  44820. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44821. if (!previousMultiTouchPanPosition.isPaning) {
  44822. previousMultiTouchPanPosition.isPaning = true;
  44823. previousMultiTouchPanPosition.isPinching = false;
  44824. previousMultiTouchPanPosition.x = ed.x;
  44825. previousMultiTouchPanPosition.y = ed.y;
  44826. return;
  44827. }
  44828. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44829. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44830. }
  44831. }
  44832. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44833. previousMultiTouchPanPosition.x = ed.x;
  44834. previousMultiTouchPanPosition.y = ed.y;
  44835. }
  44836. }
  44837. previousPinchSquaredDistance = pinchSquaredDistance;
  44838. }
  44839. }
  44840. };
  44841. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44842. this._onContextMenu = function (evt) {
  44843. evt.preventDefault();
  44844. };
  44845. if (!this.camera._useCtrlForPanning) {
  44846. element.addEventListener("contextmenu", this._onContextMenu, false);
  44847. }
  44848. this._onLostFocus = function () {
  44849. //this._keys = [];
  44850. pointA = pointB = null;
  44851. previousPinchSquaredDistance = 0;
  44852. previousMultiTouchPanPosition.isPaning = false;
  44853. previousMultiTouchPanPosition.isPinching = false;
  44854. twoFingerActivityCount = 0;
  44855. cacheSoloPointer = null;
  44856. initialDistance = 0;
  44857. };
  44858. this._onMouseMove = function (evt) {
  44859. if (!engine.isPointerLock) {
  44860. return;
  44861. }
  44862. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44863. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44864. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44865. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44866. if (!noPreventDefault) {
  44867. evt.preventDefault();
  44868. }
  44869. };
  44870. this._onGestureStart = function (e) {
  44871. if (window.MSGesture === undefined) {
  44872. return;
  44873. }
  44874. if (!_this._MSGestureHandler) {
  44875. _this._MSGestureHandler = new MSGesture();
  44876. _this._MSGestureHandler.target = element;
  44877. }
  44878. _this._MSGestureHandler.addPointer(e.pointerId);
  44879. };
  44880. this._onGesture = function (e) {
  44881. _this.camera.radius *= e.scale;
  44882. if (e.preventDefault) {
  44883. if (!noPreventDefault) {
  44884. e.stopPropagation();
  44885. e.preventDefault();
  44886. }
  44887. }
  44888. };
  44889. element.addEventListener("mousemove", this._onMouseMove, false);
  44890. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44891. element.addEventListener("MSGestureChange", this._onGesture, false);
  44892. BABYLON.Tools.RegisterTopRootEvents([
  44893. { name: "blur", handler: this._onLostFocus }
  44894. ]);
  44895. };
  44896. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44897. if (this._onLostFocus) {
  44898. BABYLON.Tools.UnregisterTopRootEvents([
  44899. { name: "blur", handler: this._onLostFocus }
  44900. ]);
  44901. }
  44902. if (element && this._observer) {
  44903. this.camera.getScene().onPointerObservable.remove(this._observer);
  44904. this._observer = null;
  44905. if (this._onContextMenu) {
  44906. element.removeEventListener("contextmenu", this._onContextMenu);
  44907. }
  44908. if (this._onMouseMove) {
  44909. element.removeEventListener("mousemove", this._onMouseMove);
  44910. }
  44911. if (this._onGestureStart) {
  44912. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44913. }
  44914. if (this._onGesture) {
  44915. element.removeEventListener("MSGestureChange", this._onGesture);
  44916. }
  44917. this._isPanClick = false;
  44918. this.pinchInwards = true;
  44919. this._onMouseMove = null;
  44920. this._onGestureStart = null;
  44921. this._onGesture = null;
  44922. this._MSGestureHandler = null;
  44923. this._onLostFocus = null;
  44924. this._onContextMenu = null;
  44925. }
  44926. };
  44927. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44928. return "ArcRotateCameraPointersInput";
  44929. };
  44930. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44931. return "pointers";
  44932. };
  44933. __decorate([
  44934. BABYLON.serialize()
  44935. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44936. __decorate([
  44937. BABYLON.serialize()
  44938. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44939. __decorate([
  44940. BABYLON.serialize()
  44941. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44942. __decorate([
  44943. BABYLON.serialize()
  44944. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44945. __decorate([
  44946. BABYLON.serialize()
  44947. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44948. __decorate([
  44949. BABYLON.serialize()
  44950. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44951. __decorate([
  44952. BABYLON.serialize()
  44953. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44954. __decorate([
  44955. BABYLON.serialize()
  44956. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44957. return ArcRotateCameraPointersInput;
  44958. }());
  44959. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44960. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44961. })(BABYLON || (BABYLON = {}));
  44962. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44963. "use strict";
  44964. var BABYLON;
  44965. (function (BABYLON) {
  44966. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44967. __extends(ArcRotateCameraInputsManager, _super);
  44968. function ArcRotateCameraInputsManager(camera) {
  44969. return _super.call(this, camera) || this;
  44970. }
  44971. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44972. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44973. return this;
  44974. };
  44975. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44976. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44977. return this;
  44978. };
  44979. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44980. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44981. return this;
  44982. };
  44983. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44984. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44985. return this;
  44986. };
  44987. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44988. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44989. return this;
  44990. };
  44991. return ArcRotateCameraInputsManager;
  44992. }(BABYLON.CameraInputsManager));
  44993. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44994. })(BABYLON || (BABYLON = {}));
  44995. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44996. "use strict";
  44997. var BABYLON;
  44998. (function (BABYLON) {
  44999. var ArcRotateCamera = /** @class */ (function (_super) {
  45000. __extends(ArcRotateCamera, _super);
  45001. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  45002. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  45003. _this.inertialAlphaOffset = 0;
  45004. _this.inertialBetaOffset = 0;
  45005. _this.inertialRadiusOffset = 0;
  45006. _this.lowerAlphaLimit = null;
  45007. _this.upperAlphaLimit = null;
  45008. _this.lowerBetaLimit = 0.01;
  45009. _this.upperBetaLimit = Math.PI;
  45010. _this.lowerRadiusLimit = null;
  45011. _this.upperRadiusLimit = null;
  45012. _this.inertialPanningX = 0;
  45013. _this.inertialPanningY = 0;
  45014. _this.pinchToPanMaxDistance = 20;
  45015. _this.panningDistanceLimit = null;
  45016. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  45017. _this.panningInertia = 0.9;
  45018. //-- end properties for backward compatibility for inputs
  45019. _this.zoomOnFactor = 1;
  45020. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  45021. _this.allowUpsideDown = true;
  45022. _this._viewMatrix = new BABYLON.Matrix();
  45023. // Panning
  45024. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  45025. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  45026. _this.checkCollisions = false;
  45027. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  45028. _this._previousPosition = BABYLON.Vector3.Zero();
  45029. _this._collisionVelocity = BABYLON.Vector3.Zero();
  45030. _this._newPosition = BABYLON.Vector3.Zero();
  45031. _this._computationVector = BABYLON.Vector3.Zero();
  45032. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  45033. if (collidedMesh === void 0) { collidedMesh = null; }
  45034. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  45035. newPosition.multiplyInPlace(_this._collider._radius);
  45036. }
  45037. if (!collidedMesh) {
  45038. _this._previousPosition.copyFrom(_this.position);
  45039. }
  45040. else {
  45041. _this.setPosition(newPosition);
  45042. if (_this.onCollide) {
  45043. _this.onCollide(collidedMesh);
  45044. }
  45045. }
  45046. // Recompute because of constraints
  45047. var cosa = Math.cos(_this.alpha);
  45048. var sina = Math.sin(_this.alpha);
  45049. var cosb = Math.cos(_this.beta);
  45050. var sinb = Math.sin(_this.beta);
  45051. if (sinb === 0) {
  45052. sinb = 0.0001;
  45053. }
  45054. var target = _this._getTargetPosition();
  45055. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  45056. target.addToRef(_this._computationVector, _this._newPosition);
  45057. _this.position.copyFrom(_this._newPosition);
  45058. var up = _this.upVector;
  45059. if (_this.allowUpsideDown && _this.beta < 0) {
  45060. up = up.clone();
  45061. up = up.negate();
  45062. }
  45063. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  45064. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  45065. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  45066. _this._collisionTriggered = false;
  45067. };
  45068. _this._target = BABYLON.Vector3.Zero();
  45069. if (target) {
  45070. _this.setTarget(target);
  45071. }
  45072. _this.alpha = alpha;
  45073. _this.beta = beta;
  45074. _this.radius = radius;
  45075. _this.getViewMatrix();
  45076. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  45077. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  45078. return _this;
  45079. }
  45080. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  45081. get: function () {
  45082. return this._target;
  45083. },
  45084. set: function (value) {
  45085. this.setTarget(value);
  45086. },
  45087. enumerable: true,
  45088. configurable: true
  45089. });
  45090. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  45091. //-- begin properties for backward compatibility for inputs
  45092. get: function () {
  45093. var pointers = this.inputs.attached["pointers"];
  45094. if (pointers)
  45095. return pointers.angularSensibilityX;
  45096. return 0;
  45097. },
  45098. set: function (value) {
  45099. var pointers = this.inputs.attached["pointers"];
  45100. if (pointers) {
  45101. pointers.angularSensibilityX = value;
  45102. }
  45103. },
  45104. enumerable: true,
  45105. configurable: true
  45106. });
  45107. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  45108. get: function () {
  45109. var pointers = this.inputs.attached["pointers"];
  45110. if (pointers)
  45111. return pointers.angularSensibilityY;
  45112. return 0;
  45113. },
  45114. set: function (value) {
  45115. var pointers = this.inputs.attached["pointers"];
  45116. if (pointers) {
  45117. pointers.angularSensibilityY = value;
  45118. }
  45119. },
  45120. enumerable: true,
  45121. configurable: true
  45122. });
  45123. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  45124. get: function () {
  45125. var pointers = this.inputs.attached["pointers"];
  45126. if (pointers)
  45127. return pointers.pinchPrecision;
  45128. return 0;
  45129. },
  45130. set: function (value) {
  45131. var pointers = this.inputs.attached["pointers"];
  45132. if (pointers) {
  45133. pointers.pinchPrecision = value;
  45134. }
  45135. },
  45136. enumerable: true,
  45137. configurable: true
  45138. });
  45139. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  45140. get: function () {
  45141. var pointers = this.inputs.attached["pointers"];
  45142. if (pointers)
  45143. return pointers.pinchDeltaPercentage;
  45144. return 0;
  45145. },
  45146. set: function (value) {
  45147. var pointers = this.inputs.attached["pointers"];
  45148. if (pointers) {
  45149. pointers.pinchDeltaPercentage = value;
  45150. }
  45151. },
  45152. enumerable: true,
  45153. configurable: true
  45154. });
  45155. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  45156. get: function () {
  45157. var pointers = this.inputs.attached["pointers"];
  45158. if (pointers)
  45159. return pointers.panningSensibility;
  45160. return 0;
  45161. },
  45162. set: function (value) {
  45163. var pointers = this.inputs.attached["pointers"];
  45164. if (pointers) {
  45165. pointers.panningSensibility = value;
  45166. }
  45167. },
  45168. enumerable: true,
  45169. configurable: true
  45170. });
  45171. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  45172. get: function () {
  45173. var keyboard = this.inputs.attached["keyboard"];
  45174. if (keyboard)
  45175. return keyboard.keysUp;
  45176. return [];
  45177. },
  45178. set: function (value) {
  45179. var keyboard = this.inputs.attached["keyboard"];
  45180. if (keyboard)
  45181. keyboard.keysUp = value;
  45182. },
  45183. enumerable: true,
  45184. configurable: true
  45185. });
  45186. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  45187. get: function () {
  45188. var keyboard = this.inputs.attached["keyboard"];
  45189. if (keyboard)
  45190. return keyboard.keysDown;
  45191. return [];
  45192. },
  45193. set: function (value) {
  45194. var keyboard = this.inputs.attached["keyboard"];
  45195. if (keyboard)
  45196. keyboard.keysDown = value;
  45197. },
  45198. enumerable: true,
  45199. configurable: true
  45200. });
  45201. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  45202. get: function () {
  45203. var keyboard = this.inputs.attached["keyboard"];
  45204. if (keyboard)
  45205. return keyboard.keysLeft;
  45206. return [];
  45207. },
  45208. set: function (value) {
  45209. var keyboard = this.inputs.attached["keyboard"];
  45210. if (keyboard)
  45211. keyboard.keysLeft = value;
  45212. },
  45213. enumerable: true,
  45214. configurable: true
  45215. });
  45216. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  45217. get: function () {
  45218. var keyboard = this.inputs.attached["keyboard"];
  45219. if (keyboard)
  45220. return keyboard.keysRight;
  45221. return [];
  45222. },
  45223. set: function (value) {
  45224. var keyboard = this.inputs.attached["keyboard"];
  45225. if (keyboard)
  45226. keyboard.keysRight = value;
  45227. },
  45228. enumerable: true,
  45229. configurable: true
  45230. });
  45231. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  45232. get: function () {
  45233. var mousewheel = this.inputs.attached["mousewheel"];
  45234. if (mousewheel)
  45235. return mousewheel.wheelPrecision;
  45236. return 0;
  45237. },
  45238. set: function (value) {
  45239. var mousewheel = this.inputs.attached["mousewheel"];
  45240. if (mousewheel)
  45241. mousewheel.wheelPrecision = value;
  45242. },
  45243. enumerable: true,
  45244. configurable: true
  45245. });
  45246. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  45247. get: function () {
  45248. var mousewheel = this.inputs.attached["mousewheel"];
  45249. if (mousewheel)
  45250. return mousewheel.wheelDeltaPercentage;
  45251. return 0;
  45252. },
  45253. set: function (value) {
  45254. var mousewheel = this.inputs.attached["mousewheel"];
  45255. if (mousewheel)
  45256. mousewheel.wheelDeltaPercentage = value;
  45257. },
  45258. enumerable: true,
  45259. configurable: true
  45260. });
  45261. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  45262. get: function () {
  45263. return this._bouncingBehavior;
  45264. },
  45265. enumerable: true,
  45266. configurable: true
  45267. });
  45268. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  45269. get: function () {
  45270. return this._bouncingBehavior != null;
  45271. },
  45272. set: function (value) {
  45273. if (value === this.useBouncingBehavior) {
  45274. return;
  45275. }
  45276. if (value) {
  45277. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  45278. this.addBehavior(this._bouncingBehavior);
  45279. }
  45280. else if (this._bouncingBehavior) {
  45281. this.removeBehavior(this._bouncingBehavior);
  45282. this._bouncingBehavior = null;
  45283. }
  45284. },
  45285. enumerable: true,
  45286. configurable: true
  45287. });
  45288. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  45289. get: function () {
  45290. return this._framingBehavior;
  45291. },
  45292. enumerable: true,
  45293. configurable: true
  45294. });
  45295. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  45296. get: function () {
  45297. return this._framingBehavior != null;
  45298. },
  45299. set: function (value) {
  45300. if (value === this.useFramingBehavior) {
  45301. return;
  45302. }
  45303. if (value) {
  45304. this._framingBehavior = new BABYLON.FramingBehavior();
  45305. this.addBehavior(this._framingBehavior);
  45306. }
  45307. else if (this._framingBehavior) {
  45308. this.removeBehavior(this._framingBehavior);
  45309. this._framingBehavior = null;
  45310. }
  45311. },
  45312. enumerable: true,
  45313. configurable: true
  45314. });
  45315. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  45316. get: function () {
  45317. return this._autoRotationBehavior;
  45318. },
  45319. enumerable: true,
  45320. configurable: true
  45321. });
  45322. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  45323. get: function () {
  45324. return this._autoRotationBehavior != null;
  45325. },
  45326. set: function (value) {
  45327. if (value === this.useAutoRotationBehavior) {
  45328. return;
  45329. }
  45330. if (value) {
  45331. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  45332. this.addBehavior(this._autoRotationBehavior);
  45333. }
  45334. else if (this._autoRotationBehavior) {
  45335. this.removeBehavior(this._autoRotationBehavior);
  45336. this._autoRotationBehavior = null;
  45337. }
  45338. },
  45339. enumerable: true,
  45340. configurable: true
  45341. });
  45342. // Cache
  45343. ArcRotateCamera.prototype._initCache = function () {
  45344. _super.prototype._initCache.call(this);
  45345. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45346. this._cache.alpha = undefined;
  45347. this._cache.beta = undefined;
  45348. this._cache.radius = undefined;
  45349. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  45350. };
  45351. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  45352. if (!ignoreParentClass) {
  45353. _super.prototype._updateCache.call(this);
  45354. }
  45355. this._cache._target.copyFrom(this._getTargetPosition());
  45356. this._cache.alpha = this.alpha;
  45357. this._cache.beta = this.beta;
  45358. this._cache.radius = this.radius;
  45359. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  45360. };
  45361. ArcRotateCamera.prototype._getTargetPosition = function () {
  45362. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  45363. var pos = this._targetHost.getAbsolutePosition();
  45364. if (this._targetBoundingCenter) {
  45365. pos.addToRef(this._targetBoundingCenter, this._target);
  45366. }
  45367. else {
  45368. this._target.copyFrom(pos);
  45369. }
  45370. }
  45371. var lockedTargetPosition = this._getLockedTargetPosition();
  45372. if (lockedTargetPosition) {
  45373. return lockedTargetPosition;
  45374. }
  45375. return this._target;
  45376. };
  45377. ArcRotateCamera.prototype.storeState = function () {
  45378. this._storedAlpha = this.alpha;
  45379. this._storedBeta = this.beta;
  45380. this._storedRadius = this.radius;
  45381. this._storedTarget = this._getTargetPosition().clone();
  45382. return _super.prototype.storeState.call(this);
  45383. };
  45384. /**
  45385. * Restored camera state. You must call storeState() first
  45386. */
  45387. ArcRotateCamera.prototype._restoreStateValues = function () {
  45388. if (!_super.prototype._restoreStateValues.call(this)) {
  45389. return false;
  45390. }
  45391. this.alpha = this._storedAlpha;
  45392. this.beta = this._storedBeta;
  45393. this.radius = this._storedRadius;
  45394. this.setTarget(this._storedTarget.clone());
  45395. this.inertialAlphaOffset = 0;
  45396. this.inertialBetaOffset = 0;
  45397. this.inertialRadiusOffset = 0;
  45398. this.inertialPanningX = 0;
  45399. this.inertialPanningY = 0;
  45400. return true;
  45401. };
  45402. // Synchronized
  45403. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  45404. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  45405. return false;
  45406. return this._cache._target.equals(this._getTargetPosition())
  45407. && this._cache.alpha === this.alpha
  45408. && this._cache.beta === this.beta
  45409. && this._cache.radius === this.radius
  45410. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  45411. };
  45412. // Methods
  45413. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  45414. var _this = this;
  45415. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  45416. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  45417. this._useCtrlForPanning = useCtrlForPanning;
  45418. this._panningMouseButton = panningMouseButton;
  45419. this.inputs.attachElement(element, noPreventDefault);
  45420. this._reset = function () {
  45421. _this.inertialAlphaOffset = 0;
  45422. _this.inertialBetaOffset = 0;
  45423. _this.inertialRadiusOffset = 0;
  45424. _this.inertialPanningX = 0;
  45425. _this.inertialPanningY = 0;
  45426. };
  45427. };
  45428. ArcRotateCamera.prototype.detachControl = function (element) {
  45429. this.inputs.detachElement(element);
  45430. if (this._reset) {
  45431. this._reset();
  45432. }
  45433. };
  45434. ArcRotateCamera.prototype._checkInputs = function () {
  45435. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45436. if (this._collisionTriggered) {
  45437. return;
  45438. }
  45439. this.inputs.checkInputs();
  45440. // Inertia
  45441. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45442. if (this.getScene().useRightHandedSystem) {
  45443. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45444. }
  45445. else {
  45446. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45447. }
  45448. this.beta += this.inertialBetaOffset;
  45449. this.radius -= this.inertialRadiusOffset;
  45450. this.inertialAlphaOffset *= this.inertia;
  45451. this.inertialBetaOffset *= this.inertia;
  45452. this.inertialRadiusOffset *= this.inertia;
  45453. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45454. this.inertialAlphaOffset = 0;
  45455. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45456. this.inertialBetaOffset = 0;
  45457. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45458. this.inertialRadiusOffset = 0;
  45459. }
  45460. // Panning inertia
  45461. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45462. if (!this._localDirection) {
  45463. this._localDirection = BABYLON.Vector3.Zero();
  45464. this._transformedDirection = BABYLON.Vector3.Zero();
  45465. }
  45466. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45467. this._localDirection.multiplyInPlace(this.panningAxis);
  45468. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45469. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45470. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45471. if (!this.panningAxis.y) {
  45472. this._transformedDirection.y = 0;
  45473. }
  45474. if (!this._targetHost) {
  45475. if (this.panningDistanceLimit) {
  45476. this._transformedDirection.addInPlace(this._target);
  45477. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45478. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45479. this._target.copyFrom(this._transformedDirection);
  45480. }
  45481. }
  45482. else {
  45483. this._target.addInPlace(this._transformedDirection);
  45484. }
  45485. }
  45486. this.inertialPanningX *= this.panningInertia;
  45487. this.inertialPanningY *= this.panningInertia;
  45488. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45489. this.inertialPanningX = 0;
  45490. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45491. this.inertialPanningY = 0;
  45492. }
  45493. // Limits
  45494. this._checkLimits();
  45495. _super.prototype._checkInputs.call(this);
  45496. };
  45497. ArcRotateCamera.prototype._checkLimits = function () {
  45498. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45499. if (this.allowUpsideDown && this.beta > Math.PI) {
  45500. this.beta = this.beta - (2 * Math.PI);
  45501. }
  45502. }
  45503. else {
  45504. if (this.beta < this.lowerBetaLimit) {
  45505. this.beta = this.lowerBetaLimit;
  45506. }
  45507. }
  45508. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45509. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45510. this.beta = this.beta + (2 * Math.PI);
  45511. }
  45512. }
  45513. else {
  45514. if (this.beta > this.upperBetaLimit) {
  45515. this.beta = this.upperBetaLimit;
  45516. }
  45517. }
  45518. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45519. this.alpha = this.lowerAlphaLimit;
  45520. }
  45521. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45522. this.alpha = this.upperAlphaLimit;
  45523. }
  45524. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45525. this.radius = this.lowerRadiusLimit;
  45526. }
  45527. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45528. this.radius = this.upperRadiusLimit;
  45529. }
  45530. };
  45531. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45532. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45533. this.radius = this._computationVector.length();
  45534. if (this.radius === 0) {
  45535. this.radius = 0.0001; // Just to avoid division by zero
  45536. }
  45537. // Alpha
  45538. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45539. if (this._computationVector.z < 0) {
  45540. this.alpha = 2 * Math.PI - this.alpha;
  45541. }
  45542. // Beta
  45543. this.beta = Math.acos(this._computationVector.y / this.radius);
  45544. this._checkLimits();
  45545. };
  45546. ArcRotateCamera.prototype.setPosition = function (position) {
  45547. if (this.position.equals(position)) {
  45548. return;
  45549. }
  45550. this.position.copyFrom(position);
  45551. this.rebuildAnglesAndRadius();
  45552. };
  45553. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45554. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45555. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45556. if (target.getBoundingInfo) {
  45557. if (toBoundingCenter) {
  45558. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45559. }
  45560. else {
  45561. this._targetBoundingCenter = null;
  45562. }
  45563. this._targetHost = target;
  45564. this._target = this._getTargetPosition();
  45565. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45566. }
  45567. else {
  45568. var newTarget = target;
  45569. var currentTarget = this._getTargetPosition();
  45570. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45571. return;
  45572. }
  45573. this._targetHost = null;
  45574. this._target = newTarget;
  45575. this._targetBoundingCenter = null;
  45576. this.onMeshTargetChangedObservable.notifyObservers(null);
  45577. }
  45578. this.rebuildAnglesAndRadius();
  45579. };
  45580. ArcRotateCamera.prototype._getViewMatrix = function () {
  45581. // Compute
  45582. var cosa = Math.cos(this.alpha);
  45583. var sina = Math.sin(this.alpha);
  45584. var cosb = Math.cos(this.beta);
  45585. var sinb = Math.sin(this.beta);
  45586. if (sinb === 0) {
  45587. sinb = 0.0001;
  45588. }
  45589. var target = this._getTargetPosition();
  45590. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45591. target.addToRef(this._computationVector, this._newPosition);
  45592. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45593. if (!this._collider) {
  45594. this._collider = new BABYLON.Collider();
  45595. }
  45596. this._collider._radius = this.collisionRadius;
  45597. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45598. this._collisionTriggered = true;
  45599. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45600. }
  45601. else {
  45602. this.position.copyFrom(this._newPosition);
  45603. var up = this.upVector;
  45604. if (this.allowUpsideDown && sinb < 0) {
  45605. up = up.clone();
  45606. up = up.negate();
  45607. }
  45608. if (this.getScene().useRightHandedSystem) {
  45609. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45610. }
  45611. else {
  45612. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45613. }
  45614. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45615. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45616. }
  45617. this._currentTarget = target;
  45618. return this._viewMatrix;
  45619. };
  45620. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45621. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45622. meshes = meshes || this.getScene().meshes;
  45623. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45624. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45625. this.radius = distance * this.zoomOnFactor;
  45626. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45627. };
  45628. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45629. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45630. var meshesOrMinMaxVector;
  45631. var distance;
  45632. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45633. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45634. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45635. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45636. }
  45637. else {
  45638. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45639. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45640. distance = minMaxVectorAndDistance.distance;
  45641. }
  45642. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45643. if (!doNotUpdateMaxZ) {
  45644. this.maxZ = distance * 2;
  45645. }
  45646. };
  45647. /**
  45648. * @override
  45649. * Override Camera.createRigCamera
  45650. */
  45651. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45652. var alphaShift = 0;
  45653. switch (this.cameraRigMode) {
  45654. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45655. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45656. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45657. case BABYLON.Camera.RIG_MODE_VR:
  45658. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45659. break;
  45660. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45661. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45662. break;
  45663. }
  45664. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45665. rigCam._cameraRigParams = {};
  45666. return rigCam;
  45667. };
  45668. /**
  45669. * @override
  45670. * Override Camera._updateRigCameras
  45671. */
  45672. ArcRotateCamera.prototype._updateRigCameras = function () {
  45673. var camLeft = this._rigCameras[0];
  45674. var camRight = this._rigCameras[1];
  45675. camLeft.beta = camRight.beta = this.beta;
  45676. camLeft.radius = camRight.radius = this.radius;
  45677. switch (this.cameraRigMode) {
  45678. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45679. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45680. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45681. case BABYLON.Camera.RIG_MODE_VR:
  45682. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45683. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45684. break;
  45685. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45686. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45687. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45688. break;
  45689. }
  45690. _super.prototype._updateRigCameras.call(this);
  45691. };
  45692. ArcRotateCamera.prototype.dispose = function () {
  45693. this.inputs.clear();
  45694. _super.prototype.dispose.call(this);
  45695. };
  45696. ArcRotateCamera.prototype.getClassName = function () {
  45697. return "ArcRotateCamera";
  45698. };
  45699. __decorate([
  45700. BABYLON.serialize()
  45701. ], ArcRotateCamera.prototype, "alpha", void 0);
  45702. __decorate([
  45703. BABYLON.serialize()
  45704. ], ArcRotateCamera.prototype, "beta", void 0);
  45705. __decorate([
  45706. BABYLON.serialize()
  45707. ], ArcRotateCamera.prototype, "radius", void 0);
  45708. __decorate([
  45709. BABYLON.serializeAsVector3("target")
  45710. ], ArcRotateCamera.prototype, "_target", void 0);
  45711. __decorate([
  45712. BABYLON.serialize()
  45713. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45714. __decorate([
  45715. BABYLON.serialize()
  45716. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45717. __decorate([
  45718. BABYLON.serialize()
  45719. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45720. __decorate([
  45721. BABYLON.serialize()
  45722. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45723. __decorate([
  45724. BABYLON.serialize()
  45725. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45726. __decorate([
  45727. BABYLON.serialize()
  45728. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45729. __decorate([
  45730. BABYLON.serialize()
  45731. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45732. __decorate([
  45733. BABYLON.serialize()
  45734. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45735. __decorate([
  45736. BABYLON.serialize()
  45737. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45738. __decorate([
  45739. BABYLON.serialize()
  45740. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45741. __decorate([
  45742. BABYLON.serialize()
  45743. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45744. __decorate([
  45745. BABYLON.serialize()
  45746. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45747. __decorate([
  45748. BABYLON.serialize()
  45749. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45750. __decorate([
  45751. BABYLON.serializeAsVector3()
  45752. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45753. __decorate([
  45754. BABYLON.serialize()
  45755. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45756. __decorate([
  45757. BABYLON.serialize()
  45758. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45759. __decorate([
  45760. BABYLON.serialize()
  45761. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45762. return ArcRotateCamera;
  45763. }(BABYLON.TargetCamera));
  45764. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45765. })(BABYLON || (BABYLON = {}));
  45766. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45767. "use strict";
  45768. var BABYLON;
  45769. (function (BABYLON) {
  45770. /**
  45771. * The HemisphericLight simulates the ambient environment light,
  45772. * so the passed direction is the light reflection direction, not the incoming direction.
  45773. */
  45774. var HemisphericLight = /** @class */ (function (_super) {
  45775. __extends(HemisphericLight, _super);
  45776. /**
  45777. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45778. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45779. * The HemisphericLight can't cast shadows.
  45780. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45781. * @param name The friendly name of the light
  45782. * @param direction The direction of the light reflection
  45783. * @param scene The scene the light belongs to
  45784. */
  45785. function HemisphericLight(name, direction, scene) {
  45786. var _this = _super.call(this, name, scene) || this;
  45787. /**
  45788. * The groundColor is the light in the opposite direction to the one specified during creation.
  45789. * 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.
  45790. */
  45791. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45792. _this.direction = direction || BABYLON.Vector3.Up();
  45793. return _this;
  45794. }
  45795. HemisphericLight.prototype._buildUniformLayout = function () {
  45796. this._uniformBuffer.addUniform("vLightData", 4);
  45797. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45798. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45799. this._uniformBuffer.addUniform("vLightGround", 3);
  45800. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45801. this._uniformBuffer.addUniform("depthValues", 2);
  45802. this._uniformBuffer.create();
  45803. };
  45804. /**
  45805. * Returns the string "HemisphericLight".
  45806. * @return The class name
  45807. */
  45808. HemisphericLight.prototype.getClassName = function () {
  45809. return "HemisphericLight";
  45810. };
  45811. /**
  45812. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45813. * Returns the updated direction.
  45814. * @param target The target the direction should point to
  45815. * @return The computed direction
  45816. */
  45817. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45818. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45819. return this.direction;
  45820. };
  45821. /**
  45822. * Returns the shadow generator associated to the light.
  45823. * @returns Always null for hemispheric lights because it does not support shadows.
  45824. */
  45825. HemisphericLight.prototype.getShadowGenerator = function () {
  45826. return null;
  45827. };
  45828. /**
  45829. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45830. * @param effect The effect to update
  45831. * @param lightIndex The index of the light in the effect to update
  45832. * @returns The hemispheric light
  45833. */
  45834. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45835. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45836. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45837. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45838. return this;
  45839. };
  45840. /**
  45841. * @ignore internal use only.
  45842. */
  45843. HemisphericLight.prototype._getWorldMatrix = function () {
  45844. if (!this._worldMatrix) {
  45845. this._worldMatrix = BABYLON.Matrix.Identity();
  45846. }
  45847. return this._worldMatrix;
  45848. };
  45849. /**
  45850. * Returns the integer 3.
  45851. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45852. */
  45853. HemisphericLight.prototype.getTypeID = function () {
  45854. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45855. };
  45856. __decorate([
  45857. BABYLON.serializeAsColor3()
  45858. ], HemisphericLight.prototype, "groundColor", void 0);
  45859. __decorate([
  45860. BABYLON.serializeAsVector3()
  45861. ], HemisphericLight.prototype, "direction", void 0);
  45862. return HemisphericLight;
  45863. }(BABYLON.Light));
  45864. BABYLON.HemisphericLight = HemisphericLight;
  45865. })(BABYLON || (BABYLON = {}));
  45866. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45867. "use strict";
  45868. var BABYLON;
  45869. (function (BABYLON) {
  45870. /**
  45871. * Base implementation of @see IShadowLight
  45872. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45873. */
  45874. var ShadowLight = /** @class */ (function (_super) {
  45875. __extends(ShadowLight, _super);
  45876. function ShadowLight() {
  45877. var _this = _super !== null && _super.apply(this, arguments) || this;
  45878. _this._needProjectionMatrixCompute = true;
  45879. return _this;
  45880. }
  45881. ShadowLight.prototype._setPosition = function (value) {
  45882. this._position = value;
  45883. };
  45884. Object.defineProperty(ShadowLight.prototype, "position", {
  45885. /**
  45886. * Sets the position the shadow will be casted from. Also use as the light position for both
  45887. * point and spot lights.
  45888. */
  45889. get: function () {
  45890. return this._position;
  45891. },
  45892. /**
  45893. * Sets the position the shadow will be casted from. Also use as the light position for both
  45894. * point and spot lights.
  45895. */
  45896. set: function (value) {
  45897. this._setPosition(value);
  45898. },
  45899. enumerable: true,
  45900. configurable: true
  45901. });
  45902. ShadowLight.prototype._setDirection = function (value) {
  45903. this._direction = value;
  45904. };
  45905. Object.defineProperty(ShadowLight.prototype, "direction", {
  45906. /**
  45907. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45908. * Also use as the light direction on spot and directional lights.
  45909. */
  45910. get: function () {
  45911. return this._direction;
  45912. },
  45913. /**
  45914. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45915. * Also use as the light direction on spot and directional lights.
  45916. */
  45917. set: function (value) {
  45918. this._setDirection(value);
  45919. },
  45920. enumerable: true,
  45921. configurable: true
  45922. });
  45923. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45924. /**
  45925. * Gets the shadow projection clipping minimum z value.
  45926. */
  45927. get: function () {
  45928. return this._shadowMinZ;
  45929. },
  45930. /**
  45931. * Sets the shadow projection clipping minimum z value.
  45932. */
  45933. set: function (value) {
  45934. this._shadowMinZ = value;
  45935. this.forceProjectionMatrixCompute();
  45936. },
  45937. enumerable: true,
  45938. configurable: true
  45939. });
  45940. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45941. /**
  45942. * Sets the shadow projection clipping maximum z value.
  45943. */
  45944. get: function () {
  45945. return this._shadowMaxZ;
  45946. },
  45947. /**
  45948. * Gets the shadow projection clipping maximum z value.
  45949. */
  45950. set: function (value) {
  45951. this._shadowMaxZ = value;
  45952. this.forceProjectionMatrixCompute();
  45953. },
  45954. enumerable: true,
  45955. configurable: true
  45956. });
  45957. /**
  45958. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45959. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45960. */
  45961. ShadowLight.prototype.computeTransformedInformation = function () {
  45962. if (this.parent && this.parent.getWorldMatrix) {
  45963. if (!this.transformedPosition) {
  45964. this.transformedPosition = BABYLON.Vector3.Zero();
  45965. }
  45966. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45967. // In case the direction is present.
  45968. if (this.direction) {
  45969. if (!this.transformedDirection) {
  45970. this.transformedDirection = BABYLON.Vector3.Zero();
  45971. }
  45972. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45973. }
  45974. return true;
  45975. }
  45976. return false;
  45977. };
  45978. /**
  45979. * Return the depth scale used for the shadow map.
  45980. * @returns the depth scale.
  45981. */
  45982. ShadowLight.prototype.getDepthScale = function () {
  45983. return 50.0;
  45984. };
  45985. /**
  45986. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45987. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45988. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45989. */
  45990. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45991. return this.transformedDirection ? this.transformedDirection : this.direction;
  45992. };
  45993. /**
  45994. * Returns the ShadowLight absolute position in the World.
  45995. * @returns the position vector in world space
  45996. */
  45997. ShadowLight.prototype.getAbsolutePosition = function () {
  45998. return this.transformedPosition ? this.transformedPosition : this.position;
  45999. };
  46000. /**
  46001. * Sets the ShadowLight direction toward the passed target.
  46002. * @param target The point tot target in local space
  46003. * @returns the updated ShadowLight direction
  46004. */
  46005. ShadowLight.prototype.setDirectionToTarget = function (target) {
  46006. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  46007. return this.direction;
  46008. };
  46009. /**
  46010. * Returns the light rotation in euler definition.
  46011. * @returns the x y z rotation in local space.
  46012. */
  46013. ShadowLight.prototype.getRotation = function () {
  46014. this.direction.normalize();
  46015. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  46016. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  46017. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  46018. };
  46019. /**
  46020. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  46021. * @returns true if a cube texture needs to be use
  46022. */
  46023. ShadowLight.prototype.needCube = function () {
  46024. return false;
  46025. };
  46026. /**
  46027. * Detects if the projection matrix requires to be recomputed this frame.
  46028. * @returns true if it requires to be recomputed otherwise, false.
  46029. */
  46030. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  46031. return this._needProjectionMatrixCompute;
  46032. };
  46033. /**
  46034. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  46035. */
  46036. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  46037. this._needProjectionMatrixCompute = true;
  46038. };
  46039. /**
  46040. * Get the world matrix of the sahdow lights.
  46041. * @ignore Internal Use Only
  46042. */
  46043. ShadowLight.prototype._getWorldMatrix = function () {
  46044. if (!this._worldMatrix) {
  46045. this._worldMatrix = BABYLON.Matrix.Identity();
  46046. }
  46047. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  46048. return this._worldMatrix;
  46049. };
  46050. /**
  46051. * Gets the minZ used for shadow according to both the scene and the light.
  46052. * @param activeCamera The camera we are returning the min for
  46053. * @returns the depth min z
  46054. */
  46055. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  46056. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  46057. };
  46058. /**
  46059. * Gets the maxZ used for shadow according to both the scene and the light.
  46060. * @param activeCamera The camera we are returning the max for
  46061. * @returns the depth max z
  46062. */
  46063. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  46064. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  46065. };
  46066. /**
  46067. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  46068. * @param matrix The materix to updated with the projection information
  46069. * @param viewMatrix The transform matrix of the light
  46070. * @param renderList The list of mesh to render in the map
  46071. * @returns The current light
  46072. */
  46073. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46074. if (this.customProjectionMatrixBuilder) {
  46075. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  46076. }
  46077. else {
  46078. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46079. }
  46080. return this;
  46081. };
  46082. __decorate([
  46083. BABYLON.serializeAsVector3()
  46084. ], ShadowLight.prototype, "position", null);
  46085. __decorate([
  46086. BABYLON.serializeAsVector3()
  46087. ], ShadowLight.prototype, "direction", null);
  46088. __decorate([
  46089. BABYLON.serialize()
  46090. ], ShadowLight.prototype, "shadowMinZ", null);
  46091. __decorate([
  46092. BABYLON.serialize()
  46093. ], ShadowLight.prototype, "shadowMaxZ", null);
  46094. return ShadowLight;
  46095. }(BABYLON.Light));
  46096. BABYLON.ShadowLight = ShadowLight;
  46097. })(BABYLON || (BABYLON = {}));
  46098. //# sourceMappingURL=babylon.shadowLight.js.map
  46099. "use strict";
  46100. var BABYLON;
  46101. (function (BABYLON) {
  46102. /**
  46103. * A point light is a light defined by an unique point in world space.
  46104. * The light is emitted in every direction from this point.
  46105. * A good example of a point light is a standard light bulb.
  46106. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46107. */
  46108. var PointLight = /** @class */ (function (_super) {
  46109. __extends(PointLight, _super);
  46110. /**
  46111. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  46112. * A PointLight emits the light in every direction.
  46113. * It can cast shadows.
  46114. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  46115. * ```javascript
  46116. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  46117. * ```
  46118. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46119. * @param name The light friendly name
  46120. * @param position The position of the point light in the scene
  46121. * @param scene The scene the lights belongs to
  46122. */
  46123. function PointLight(name, position, scene) {
  46124. var _this = _super.call(this, name, scene) || this;
  46125. _this._shadowAngle = Math.PI / 2;
  46126. _this.position = position;
  46127. return _this;
  46128. }
  46129. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  46130. /**
  46131. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46132. * This specifies what angle the shadow will use to be created.
  46133. *
  46134. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46135. */
  46136. get: function () {
  46137. return this._shadowAngle;
  46138. },
  46139. /**
  46140. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46141. * This specifies what angle the shadow will use to be created.
  46142. *
  46143. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46144. */
  46145. set: function (value) {
  46146. this._shadowAngle = value;
  46147. this.forceProjectionMatrixCompute();
  46148. },
  46149. enumerable: true,
  46150. configurable: true
  46151. });
  46152. Object.defineProperty(PointLight.prototype, "direction", {
  46153. /**
  46154. * Gets the direction if it has been set.
  46155. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46156. */
  46157. get: function () {
  46158. return this._direction;
  46159. },
  46160. /**
  46161. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46162. */
  46163. set: function (value) {
  46164. var previousNeedCube = this.needCube();
  46165. this._direction = value;
  46166. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  46167. this._shadowGenerator.recreateShadowMap();
  46168. }
  46169. },
  46170. enumerable: true,
  46171. configurable: true
  46172. });
  46173. /**
  46174. * Returns the string "PointLight"
  46175. * @returns the class name
  46176. */
  46177. PointLight.prototype.getClassName = function () {
  46178. return "PointLight";
  46179. };
  46180. /**
  46181. * Returns the integer 0.
  46182. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46183. */
  46184. PointLight.prototype.getTypeID = function () {
  46185. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  46186. };
  46187. /**
  46188. * Specifies wether or not the shadowmap should be a cube texture.
  46189. * @returns true if the shadowmap needs to be a cube texture.
  46190. */
  46191. PointLight.prototype.needCube = function () {
  46192. return !this.direction;
  46193. };
  46194. /**
  46195. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  46196. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46197. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46198. */
  46199. PointLight.prototype.getShadowDirection = function (faceIndex) {
  46200. if (this.direction) {
  46201. return _super.prototype.getShadowDirection.call(this, faceIndex);
  46202. }
  46203. else {
  46204. switch (faceIndex) {
  46205. case 0:
  46206. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  46207. case 1:
  46208. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  46209. case 2:
  46210. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  46211. case 3:
  46212. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  46213. case 4:
  46214. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  46215. case 5:
  46216. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  46217. }
  46218. }
  46219. return BABYLON.Vector3.Zero();
  46220. };
  46221. /**
  46222. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  46223. * - fov = PI / 2
  46224. * - aspect ratio : 1.0
  46225. * - z-near and far equal to the active camera minZ and maxZ.
  46226. * Returns the PointLight.
  46227. */
  46228. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46229. var activeCamera = this.getScene().activeCamera;
  46230. if (!activeCamera) {
  46231. return;
  46232. }
  46233. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46234. };
  46235. PointLight.prototype._buildUniformLayout = function () {
  46236. this._uniformBuffer.addUniform("vLightData", 4);
  46237. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46238. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46239. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46240. this._uniformBuffer.addUniform("depthValues", 2);
  46241. this._uniformBuffer.create();
  46242. };
  46243. /**
  46244. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  46245. * @param effect The effect to update
  46246. * @param lightIndex The index of the light in the effect to update
  46247. * @returns The point light
  46248. */
  46249. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  46250. if (this.computeTransformedInformation()) {
  46251. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  46252. return this;
  46253. }
  46254. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  46255. return this;
  46256. };
  46257. __decorate([
  46258. BABYLON.serialize()
  46259. ], PointLight.prototype, "shadowAngle", null);
  46260. return PointLight;
  46261. }(BABYLON.ShadowLight));
  46262. BABYLON.PointLight = PointLight;
  46263. })(BABYLON || (BABYLON = {}));
  46264. //# sourceMappingURL=babylon.pointLight.js.map
  46265. "use strict";
  46266. var BABYLON;
  46267. (function (BABYLON) {
  46268. /**
  46269. * A directional light is defined by a direction (what a surprise!).
  46270. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  46271. * 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.
  46272. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46273. */
  46274. var DirectionalLight = /** @class */ (function (_super) {
  46275. __extends(DirectionalLight, _super);
  46276. /**
  46277. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  46278. * The directional light is emitted from everywhere in the given direction.
  46279. * It can cast shawdows.
  46280. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46281. * @param name The friendly name of the light
  46282. * @param direction The direction of the light
  46283. * @param scene The scene the light belongs to
  46284. */
  46285. function DirectionalLight(name, direction, scene) {
  46286. var _this = _super.call(this, name, scene) || this;
  46287. _this._shadowFrustumSize = 0;
  46288. _this._shadowOrthoScale = 0.1;
  46289. /**
  46290. * Automatically compute the projection matrix to best fit (including all the casters)
  46291. * on each frame.
  46292. */
  46293. _this.autoUpdateExtends = true;
  46294. // Cache
  46295. _this._orthoLeft = Number.MAX_VALUE;
  46296. _this._orthoRight = Number.MIN_VALUE;
  46297. _this._orthoTop = Number.MIN_VALUE;
  46298. _this._orthoBottom = Number.MAX_VALUE;
  46299. _this.position = direction.scale(-1.0);
  46300. _this.direction = direction;
  46301. return _this;
  46302. }
  46303. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  46304. /**
  46305. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  46306. */
  46307. get: function () {
  46308. return this._shadowFrustumSize;
  46309. },
  46310. /**
  46311. * Specifies a fix frustum size for the shadow generation.
  46312. */
  46313. set: function (value) {
  46314. this._shadowFrustumSize = value;
  46315. this.forceProjectionMatrixCompute();
  46316. },
  46317. enumerable: true,
  46318. configurable: true
  46319. });
  46320. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  46321. /**
  46322. * Gets the shadow projection scale against the optimal computed one.
  46323. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46324. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46325. */
  46326. get: function () {
  46327. return this._shadowOrthoScale;
  46328. },
  46329. /**
  46330. * Sets the shadow projection scale against the optimal computed one.
  46331. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46332. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46333. */
  46334. set: function (value) {
  46335. this._shadowOrthoScale = value;
  46336. this.forceProjectionMatrixCompute();
  46337. },
  46338. enumerable: true,
  46339. configurable: true
  46340. });
  46341. /**
  46342. * Returns the string "DirectionalLight".
  46343. * @return The class name
  46344. */
  46345. DirectionalLight.prototype.getClassName = function () {
  46346. return "DirectionalLight";
  46347. };
  46348. /**
  46349. * Returns the integer 1.
  46350. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46351. */
  46352. DirectionalLight.prototype.getTypeID = function () {
  46353. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  46354. };
  46355. /**
  46356. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  46357. * Returns the DirectionalLight Shadow projection matrix.
  46358. */
  46359. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46360. if (this.shadowFrustumSize > 0) {
  46361. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  46362. }
  46363. else {
  46364. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46365. }
  46366. };
  46367. /**
  46368. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  46369. * Returns the DirectionalLight Shadow projection matrix.
  46370. */
  46371. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  46372. var activeCamera = this.getScene().activeCamera;
  46373. if (!activeCamera) {
  46374. return;
  46375. }
  46376. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  46377. };
  46378. /**
  46379. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  46380. * Returns the DirectionalLight Shadow projection matrix.
  46381. */
  46382. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46383. var activeCamera = this.getScene().activeCamera;
  46384. if (!activeCamera) {
  46385. return;
  46386. }
  46387. // Check extends
  46388. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  46389. var tempVector3 = BABYLON.Vector3.Zero();
  46390. this._orthoLeft = Number.MAX_VALUE;
  46391. this._orthoRight = Number.MIN_VALUE;
  46392. this._orthoTop = Number.MIN_VALUE;
  46393. this._orthoBottom = Number.MAX_VALUE;
  46394. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  46395. var mesh = renderList[meshIndex];
  46396. if (!mesh) {
  46397. continue;
  46398. }
  46399. var boundingInfo = mesh.getBoundingInfo();
  46400. var boundingBox = boundingInfo.boundingBox;
  46401. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  46402. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  46403. if (tempVector3.x < this._orthoLeft)
  46404. this._orthoLeft = tempVector3.x;
  46405. if (tempVector3.y < this._orthoBottom)
  46406. this._orthoBottom = tempVector3.y;
  46407. if (tempVector3.x > this._orthoRight)
  46408. this._orthoRight = tempVector3.x;
  46409. if (tempVector3.y > this._orthoTop)
  46410. this._orthoTop = tempVector3.y;
  46411. }
  46412. }
  46413. }
  46414. var xOffset = this._orthoRight - this._orthoLeft;
  46415. var yOffset = this._orthoTop - this._orthoBottom;
  46416. 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);
  46417. };
  46418. DirectionalLight.prototype._buildUniformLayout = function () {
  46419. this._uniformBuffer.addUniform("vLightData", 4);
  46420. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46421. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46422. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46423. this._uniformBuffer.addUniform("depthValues", 2);
  46424. this._uniformBuffer.create();
  46425. };
  46426. /**
  46427. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  46428. * @param effect The effect to update
  46429. * @param lightIndex The index of the light in the effect to update
  46430. * @returns The directional light
  46431. */
  46432. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  46433. if (this.computeTransformedInformation()) {
  46434. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  46435. return this;
  46436. }
  46437. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  46438. return this;
  46439. };
  46440. /**
  46441. * Gets the minZ used for shadow according to both the scene and the light.
  46442. *
  46443. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46444. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46445. * @param activeCamera The camera we are returning the min for
  46446. * @returns the depth min z
  46447. */
  46448. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46449. return 1;
  46450. };
  46451. /**
  46452. * Gets the maxZ used for shadow according to both the scene and the light.
  46453. *
  46454. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46455. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46456. * @param activeCamera The camera we are returning the max for
  46457. * @returns the depth max z
  46458. */
  46459. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46460. return 1;
  46461. };
  46462. __decorate([
  46463. BABYLON.serialize()
  46464. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46465. __decorate([
  46466. BABYLON.serialize()
  46467. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46468. __decorate([
  46469. BABYLON.serialize()
  46470. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46471. return DirectionalLight;
  46472. }(BABYLON.ShadowLight));
  46473. BABYLON.DirectionalLight = DirectionalLight;
  46474. })(BABYLON || (BABYLON = {}));
  46475. //# sourceMappingURL=babylon.directionalLight.js.map
  46476. "use strict";
  46477. var BABYLON;
  46478. (function (BABYLON) {
  46479. /**
  46480. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46481. * These values define a cone of light starting from the position, emitting toward the direction.
  46482. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46483. * and the exponent defines the speed of the decay of the light with distance (reach).
  46484. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46485. */
  46486. var SpotLight = /** @class */ (function (_super) {
  46487. __extends(SpotLight, _super);
  46488. /**
  46489. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46490. * It can cast shadows.
  46491. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46492. * @param name The light friendly name
  46493. * @param position The position of the spot light in the scene
  46494. * @param direction The direction of the light in the scene
  46495. * @param angle The cone angle of the light in Radians
  46496. * @param exponent The light decay speed with the distance from the emission spot
  46497. * @param scene The scene the lights belongs to
  46498. */
  46499. function SpotLight(name, position, direction, angle, exponent, scene) {
  46500. var _this = _super.call(this, name, scene) || this;
  46501. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46502. _this._projectionTextureLightNear = 1e-6;
  46503. _this._projectionTextureLightFar = 1000.0;
  46504. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46505. _this._projectionTextureViewLightDirty = true;
  46506. _this._projectionTextureProjectionLightDirty = true;
  46507. _this._projectionTextureDirty = true;
  46508. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46509. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46510. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46511. _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);
  46512. _this.position = position;
  46513. _this.direction = direction;
  46514. _this.angle = angle;
  46515. _this.exponent = exponent;
  46516. return _this;
  46517. }
  46518. Object.defineProperty(SpotLight.prototype, "angle", {
  46519. /**
  46520. * Gets the cone angle of the spot light in Radians.
  46521. */
  46522. get: function () {
  46523. return this._angle;
  46524. },
  46525. /**
  46526. * Sets the cone angle of the spot light in Radians.
  46527. */
  46528. set: function (value) {
  46529. this._angle = value;
  46530. this._projectionTextureProjectionLightDirty = true;
  46531. this.forceProjectionMatrixCompute();
  46532. },
  46533. enumerable: true,
  46534. configurable: true
  46535. });
  46536. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46537. /**
  46538. * Allows scaling the angle of the light for shadow generation only.
  46539. */
  46540. get: function () {
  46541. return this._shadowAngleScale;
  46542. },
  46543. /**
  46544. * Allows scaling the angle of the light for shadow generation only.
  46545. */
  46546. set: function (value) {
  46547. this._shadowAngleScale = value;
  46548. this.forceProjectionMatrixCompute();
  46549. },
  46550. enumerable: true,
  46551. configurable: true
  46552. });
  46553. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46554. /**
  46555. * Allows reading the projecton texture
  46556. */
  46557. get: function () {
  46558. return this._projectionTextureMatrix;
  46559. },
  46560. enumerable: true,
  46561. configurable: true
  46562. });
  46563. ;
  46564. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46565. /**
  46566. * Gets the near clip of the Spotlight for texture projection.
  46567. */
  46568. get: function () {
  46569. return this._projectionTextureLightNear;
  46570. },
  46571. /**
  46572. * Sets the near clip of the Spotlight for texture projection.
  46573. */
  46574. set: function (value) {
  46575. this._projectionTextureLightNear = value;
  46576. this._projectionTextureProjectionLightDirty = true;
  46577. },
  46578. enumerable: true,
  46579. configurable: true
  46580. });
  46581. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46582. /**
  46583. * Gets the far clip of the Spotlight for texture projection.
  46584. */
  46585. get: function () {
  46586. return this._projectionTextureLightFar;
  46587. },
  46588. /**
  46589. * Sets the far clip of the Spotlight for texture projection.
  46590. */
  46591. set: function (value) {
  46592. this._projectionTextureLightFar = value;
  46593. this._projectionTextureProjectionLightDirty = true;
  46594. },
  46595. enumerable: true,
  46596. configurable: true
  46597. });
  46598. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46599. /**
  46600. * Gets the Up vector of the Spotlight for texture projection.
  46601. */
  46602. get: function () {
  46603. return this._projectionTextureUpDirection;
  46604. },
  46605. /**
  46606. * Sets the Up vector of the Spotlight for texture projection.
  46607. */
  46608. set: function (value) {
  46609. this._projectionTextureUpDirection = value;
  46610. this._projectionTextureProjectionLightDirty = true;
  46611. },
  46612. enumerable: true,
  46613. configurable: true
  46614. });
  46615. ;
  46616. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46617. /**
  46618. * Gets the projection texture of the light.
  46619. */
  46620. get: function () {
  46621. return this._projectionTexture;
  46622. },
  46623. /**
  46624. * Sets the projection texture of the light.
  46625. */
  46626. set: function (value) {
  46627. this._projectionTexture = value;
  46628. this._projectionTextureDirty = true;
  46629. },
  46630. enumerable: true,
  46631. configurable: true
  46632. });
  46633. /**
  46634. * Returns the string "SpotLight".
  46635. * @returns the class name
  46636. */
  46637. SpotLight.prototype.getClassName = function () {
  46638. return "SpotLight";
  46639. };
  46640. /**
  46641. * Returns the integer 2.
  46642. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46643. */
  46644. SpotLight.prototype.getTypeID = function () {
  46645. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46646. };
  46647. /**
  46648. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46649. */
  46650. SpotLight.prototype._setDirection = function (value) {
  46651. _super.prototype._setDirection.call(this, value);
  46652. this._projectionTextureViewLightDirty = true;
  46653. };
  46654. /**
  46655. * Overrides the position setter to recompute the projection texture view light Matrix.
  46656. */
  46657. SpotLight.prototype._setPosition = function (value) {
  46658. _super.prototype._setPosition.call(this, value);
  46659. this._projectionTextureViewLightDirty = true;
  46660. };
  46661. /**
  46662. * 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.
  46663. * Returns the SpotLight.
  46664. */
  46665. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46666. var activeCamera = this.getScene().activeCamera;
  46667. if (!activeCamera) {
  46668. return;
  46669. }
  46670. this._shadowAngleScale = this._shadowAngleScale || 1;
  46671. var angle = this._shadowAngleScale * this._angle;
  46672. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46673. };
  46674. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46675. this._projectionTextureViewLightDirty = false;
  46676. this._projectionTextureDirty = true;
  46677. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46678. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46679. };
  46680. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46681. this._projectionTextureProjectionLightDirty = false;
  46682. this._projectionTextureDirty = true;
  46683. var light_far = this.projectionTextureLightFar;
  46684. var light_near = this.projectionTextureLightNear;
  46685. var P = light_far / (light_far - light_near);
  46686. var Q = -P * light_near;
  46687. var S = 1.0 / Math.tan(this._angle / 2.0);
  46688. var A = 1.0;
  46689. 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);
  46690. };
  46691. /**
  46692. * Main function for light texture projection matrix computing.
  46693. */
  46694. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46695. this._projectionTextureDirty = false;
  46696. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46697. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46698. };
  46699. SpotLight.prototype._buildUniformLayout = function () {
  46700. this._uniformBuffer.addUniform("vLightData", 4);
  46701. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46702. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46703. this._uniformBuffer.addUniform("vLightDirection", 3);
  46704. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46705. this._uniformBuffer.addUniform("depthValues", 2);
  46706. this._uniformBuffer.create();
  46707. };
  46708. /**
  46709. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46710. * @param effect The effect to update
  46711. * @param lightIndex The index of the light in the effect to update
  46712. * @returns The spot light
  46713. */
  46714. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46715. var normalizeDirection;
  46716. if (this.computeTransformedInformation()) {
  46717. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46718. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46719. }
  46720. else {
  46721. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46722. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46723. }
  46724. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46725. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46726. if (this._projectionTextureViewLightDirty) {
  46727. this._computeProjectionTextureViewLightMatrix();
  46728. }
  46729. if (this._projectionTextureProjectionLightDirty) {
  46730. this._computeProjectionTextureProjectionLightMatrix();
  46731. }
  46732. if (this._projectionTextureDirty) {
  46733. this._computeProjectionTextureMatrix();
  46734. }
  46735. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46736. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46737. }
  46738. return this;
  46739. };
  46740. /**
  46741. * Disposes the light and the associated resources.
  46742. */
  46743. SpotLight.prototype.dispose = function () {
  46744. _super.prototype.dispose.call(this);
  46745. if (this._projectionTexture) {
  46746. this._projectionTexture.dispose();
  46747. }
  46748. };
  46749. __decorate([
  46750. BABYLON.serialize()
  46751. ], SpotLight.prototype, "angle", null);
  46752. __decorate([
  46753. BABYLON.serialize()
  46754. ], SpotLight.prototype, "shadowAngleScale", null);
  46755. __decorate([
  46756. BABYLON.serialize()
  46757. ], SpotLight.prototype, "exponent", void 0);
  46758. __decorate([
  46759. BABYLON.serialize()
  46760. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46761. __decorate([
  46762. BABYLON.serialize()
  46763. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46764. __decorate([
  46765. BABYLON.serialize()
  46766. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46767. __decorate([
  46768. BABYLON.serializeAsTexture("projectedLightTexture")
  46769. ], SpotLight.prototype, "_projectionTexture", void 0);
  46770. return SpotLight;
  46771. }(BABYLON.ShadowLight));
  46772. BABYLON.SpotLight = SpotLight;
  46773. })(BABYLON || (BABYLON = {}));
  46774. //# sourceMappingURL=babylon.spotLight.js.map
  46775. "use strict";
  46776. var BABYLON;
  46777. (function (BABYLON) {
  46778. /**
  46779. * Class used to override all child animations of a given target
  46780. */
  46781. var AnimationPropertiesOverride = /** @class */ (function () {
  46782. function AnimationPropertiesOverride() {
  46783. /**
  46784. * Gets or sets a value indicating if animation blending must be used
  46785. */
  46786. this.enableBlending = false;
  46787. /**
  46788. * Gets or sets the blending speed to use when enableBlending is true
  46789. */
  46790. this.blendingSpeed = 0.01;
  46791. /**
  46792. * Gets or sets the default loop mode to use
  46793. */
  46794. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46795. }
  46796. return AnimationPropertiesOverride;
  46797. }());
  46798. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46799. })(BABYLON || (BABYLON = {}));
  46800. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46801. "use strict";
  46802. var BABYLON;
  46803. (function (BABYLON) {
  46804. var AnimationRange = /** @class */ (function () {
  46805. function AnimationRange(name, from, to) {
  46806. this.name = name;
  46807. this.from = from;
  46808. this.to = to;
  46809. }
  46810. AnimationRange.prototype.clone = function () {
  46811. return new AnimationRange(this.name, this.from, this.to);
  46812. };
  46813. return AnimationRange;
  46814. }());
  46815. BABYLON.AnimationRange = AnimationRange;
  46816. /**
  46817. * Composed of a frame, and an action function
  46818. */
  46819. var AnimationEvent = /** @class */ (function () {
  46820. function AnimationEvent(frame, action, onlyOnce) {
  46821. this.frame = frame;
  46822. this.action = action;
  46823. this.onlyOnce = onlyOnce;
  46824. this.isDone = false;
  46825. }
  46826. return AnimationEvent;
  46827. }());
  46828. BABYLON.AnimationEvent = AnimationEvent;
  46829. var PathCursor = /** @class */ (function () {
  46830. function PathCursor(path) {
  46831. this.path = path;
  46832. this._onchange = new Array();
  46833. this.value = 0;
  46834. this.animations = new Array();
  46835. }
  46836. PathCursor.prototype.getPoint = function () {
  46837. var point = this.path.getPointAtLengthPosition(this.value);
  46838. return new BABYLON.Vector3(point.x, 0, point.y);
  46839. };
  46840. PathCursor.prototype.moveAhead = function (step) {
  46841. if (step === void 0) { step = 0.002; }
  46842. this.move(step);
  46843. return this;
  46844. };
  46845. PathCursor.prototype.moveBack = function (step) {
  46846. if (step === void 0) { step = 0.002; }
  46847. this.move(-step);
  46848. return this;
  46849. };
  46850. PathCursor.prototype.move = function (step) {
  46851. if (Math.abs(step) > 1) {
  46852. throw "step size should be less than 1.";
  46853. }
  46854. this.value += step;
  46855. this.ensureLimits();
  46856. this.raiseOnChange();
  46857. return this;
  46858. };
  46859. PathCursor.prototype.ensureLimits = function () {
  46860. while (this.value > 1) {
  46861. this.value -= 1;
  46862. }
  46863. while (this.value < 0) {
  46864. this.value += 1;
  46865. }
  46866. return this;
  46867. };
  46868. // used by animation engine
  46869. PathCursor.prototype.raiseOnChange = function () {
  46870. var _this = this;
  46871. this._onchange.forEach(function (f) { return f(_this); });
  46872. return this;
  46873. };
  46874. PathCursor.prototype.onchange = function (f) {
  46875. this._onchange.push(f);
  46876. return this;
  46877. };
  46878. return PathCursor;
  46879. }());
  46880. BABYLON.PathCursor = PathCursor;
  46881. var AnimationKeyInterpolation;
  46882. (function (AnimationKeyInterpolation) {
  46883. /**
  46884. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46885. */
  46886. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46887. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46888. var Animation = /** @class */ (function () {
  46889. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46890. this.name = name;
  46891. this.targetProperty = targetProperty;
  46892. this.framePerSecond = framePerSecond;
  46893. this.dataType = dataType;
  46894. this.loopMode = loopMode;
  46895. this.enableBlending = enableBlending;
  46896. this._runtimeAnimations = new Array();
  46897. // The set of event that will be linked to this animation
  46898. this._events = new Array();
  46899. this.blendingSpeed = 0.01;
  46900. this._ranges = {};
  46901. this.targetPropertyPath = targetProperty.split(".");
  46902. this.dataType = dataType;
  46903. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46904. }
  46905. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46906. var dataType = undefined;
  46907. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46908. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46909. }
  46910. else if (from instanceof BABYLON.Quaternion) {
  46911. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46912. }
  46913. else if (from instanceof BABYLON.Vector3) {
  46914. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46915. }
  46916. else if (from instanceof BABYLON.Vector2) {
  46917. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46918. }
  46919. else if (from instanceof BABYLON.Color3) {
  46920. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46921. }
  46922. else if (from instanceof BABYLON.Size) {
  46923. dataType = Animation.ANIMATIONTYPE_SIZE;
  46924. }
  46925. if (dataType == undefined) {
  46926. return null;
  46927. }
  46928. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46929. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46930. animation.setKeys(keys);
  46931. if (easingFunction !== undefined) {
  46932. animation.setEasingFunction(easingFunction);
  46933. }
  46934. return animation;
  46935. };
  46936. /**
  46937. * Sets up an animation.
  46938. * @param property the property to animate
  46939. * @param animationType the animation type to apply
  46940. * @param easingFunction the easing function used in the animation
  46941. * @returns The created animation
  46942. */
  46943. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46944. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46945. animation.setEasingFunction(easingFunction);
  46946. return animation;
  46947. };
  46948. /**
  46949. * Create and start an animation on a node
  46950. * @param {string} name defines the name of the global animation that will be run on all nodes
  46951. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46952. * @param {string} targetProperty defines property to animate
  46953. * @param {number} framePerSecond defines the number of frame per second yo use
  46954. * @param {number} totalFrame defines the number of frames in total
  46955. * @param {any} from defines the initial value
  46956. * @param {any} to defines the final value
  46957. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46958. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46959. * @param onAnimationEnd defines the callback to call when animation end
  46960. * @returns the animatable created for this animation
  46961. */
  46962. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46963. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46964. if (!animation) {
  46965. return null;
  46966. }
  46967. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46968. };
  46969. /**
  46970. * Create and start an animation on a node and its descendants
  46971. * @param {string} name defines the name of the global animation that will be run on all nodes
  46972. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46973. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  46974. * @param {string} targetProperty defines property to animate
  46975. * @param {number} framePerSecond defines the number of frame per second yo use
  46976. * @param {number} totalFrame defines the number of frames in total
  46977. * @param {any} from defines the initial value
  46978. * @param {any} to defines the final value
  46979. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46980. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46981. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46982. * @returns the list of animatables created for all nodes
  46983. * @example https://www.babylonjs-playground.com/#MH0VLI
  46984. */
  46985. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46986. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46987. if (!animation) {
  46988. return null;
  46989. }
  46990. var scene = node.getScene();
  46991. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46992. };
  46993. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46994. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46995. if (!animation) {
  46996. return null;
  46997. }
  46998. node.animations.push(animation);
  46999. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47000. };
  47001. /**
  47002. * Transition property of the Camera to the target Value.
  47003. * @param property The property to transition
  47004. * @param targetValue The target Value of the property
  47005. * @param host The object where the property to animate belongs
  47006. * @param scene Scene used to run the animation
  47007. * @param frameRate Framerate (in frame/s) to use
  47008. * @param transition The transition type we want to use
  47009. * @param duration The duration of the animation, in milliseconds
  47010. * @param onAnimationEnd Call back trigger at the end of the animation.
  47011. */
  47012. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  47013. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  47014. if (duration <= 0) {
  47015. host[property] = targetValue;
  47016. if (onAnimationEnd) {
  47017. onAnimationEnd();
  47018. }
  47019. return null;
  47020. }
  47021. var endFrame = frameRate * (duration / 1000);
  47022. transition.setKeys([{
  47023. frame: 0,
  47024. value: host[property].clone ? host[property].clone() : host[property]
  47025. },
  47026. {
  47027. frame: endFrame,
  47028. value: targetValue
  47029. }]);
  47030. if (!host.animations) {
  47031. host.animations = [];
  47032. }
  47033. host.animations.push(transition);
  47034. var animation = scene.beginAnimation(host, 0, endFrame, false);
  47035. animation.onAnimationEnd = onAnimationEnd;
  47036. return animation;
  47037. };
  47038. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  47039. /**
  47040. * Return the array of runtime animations currently using this animation
  47041. */
  47042. get: function () {
  47043. return this._runtimeAnimations;
  47044. },
  47045. enumerable: true,
  47046. configurable: true
  47047. });
  47048. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  47049. get: function () {
  47050. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  47051. var runtimeAnimation = _a[_i];
  47052. if (!runtimeAnimation.isStopped) {
  47053. return true;
  47054. }
  47055. }
  47056. return false;
  47057. },
  47058. enumerable: true,
  47059. configurable: true
  47060. });
  47061. // Methods
  47062. /**
  47063. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  47064. */
  47065. Animation.prototype.toString = function (fullDetails) {
  47066. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  47067. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  47068. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  47069. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  47070. if (fullDetails) {
  47071. ret += ", Ranges: {";
  47072. var first = true;
  47073. for (var name in this._ranges) {
  47074. if (first) {
  47075. ret += ", ";
  47076. first = false;
  47077. }
  47078. ret += name;
  47079. }
  47080. ret += "}";
  47081. }
  47082. return ret;
  47083. };
  47084. /**
  47085. * Add an event to this animation.
  47086. */
  47087. Animation.prototype.addEvent = function (event) {
  47088. this._events.push(event);
  47089. };
  47090. /**
  47091. * Remove all events found at the given frame
  47092. * @param frame
  47093. */
  47094. Animation.prototype.removeEvents = function (frame) {
  47095. for (var index = 0; index < this._events.length; index++) {
  47096. if (this._events[index].frame === frame) {
  47097. this._events.splice(index, 1);
  47098. index--;
  47099. }
  47100. }
  47101. };
  47102. Animation.prototype.getEvents = function () {
  47103. return this._events;
  47104. };
  47105. Animation.prototype.createRange = function (name, from, to) {
  47106. // check name not already in use; could happen for bones after serialized
  47107. if (!this._ranges[name]) {
  47108. this._ranges[name] = new AnimationRange(name, from, to);
  47109. }
  47110. };
  47111. Animation.prototype.deleteRange = function (name, deleteFrames) {
  47112. if (deleteFrames === void 0) { deleteFrames = true; }
  47113. var range = this._ranges[name];
  47114. if (!range) {
  47115. return;
  47116. }
  47117. if (deleteFrames) {
  47118. var from = range.from;
  47119. var to = range.to;
  47120. // this loop MUST go high to low for multiple splices to work
  47121. for (var key = this._keys.length - 1; key >= 0; key--) {
  47122. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  47123. this._keys.splice(key, 1);
  47124. }
  47125. }
  47126. }
  47127. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  47128. };
  47129. Animation.prototype.getRange = function (name) {
  47130. return this._ranges[name];
  47131. };
  47132. Animation.prototype.getKeys = function () {
  47133. return this._keys;
  47134. };
  47135. Animation.prototype.getHighestFrame = function () {
  47136. var ret = 0;
  47137. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  47138. if (ret < this._keys[key].frame) {
  47139. ret = this._keys[key].frame;
  47140. }
  47141. }
  47142. return ret;
  47143. };
  47144. Animation.prototype.getEasingFunction = function () {
  47145. return this._easingFunction;
  47146. };
  47147. Animation.prototype.setEasingFunction = function (easingFunction) {
  47148. this._easingFunction = easingFunction;
  47149. };
  47150. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  47151. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  47152. };
  47153. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47154. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47155. };
  47156. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  47157. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  47158. };
  47159. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47160. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  47161. };
  47162. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  47163. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  47164. };
  47165. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47166. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47167. };
  47168. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  47169. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  47170. };
  47171. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47172. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47173. };
  47174. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  47175. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  47176. };
  47177. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  47178. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  47179. };
  47180. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  47181. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  47182. };
  47183. Animation.prototype.clone = function () {
  47184. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  47185. clone.enableBlending = this.enableBlending;
  47186. clone.blendingSpeed = this.blendingSpeed;
  47187. if (this._keys) {
  47188. clone.setKeys(this._keys);
  47189. }
  47190. if (this._ranges) {
  47191. clone._ranges = {};
  47192. for (var name in this._ranges) {
  47193. var range = this._ranges[name];
  47194. if (!range) {
  47195. continue;
  47196. }
  47197. clone._ranges[name] = range.clone();
  47198. }
  47199. }
  47200. return clone;
  47201. };
  47202. Animation.prototype.setKeys = function (values) {
  47203. this._keys = values.slice(0);
  47204. };
  47205. Animation.prototype.serialize = function () {
  47206. var serializationObject = {};
  47207. serializationObject.name = this.name;
  47208. serializationObject.property = this.targetProperty;
  47209. serializationObject.framePerSecond = this.framePerSecond;
  47210. serializationObject.dataType = this.dataType;
  47211. serializationObject.loopBehavior = this.loopMode;
  47212. serializationObject.enableBlending = this.enableBlending;
  47213. serializationObject.blendingSpeed = this.blendingSpeed;
  47214. var dataType = this.dataType;
  47215. serializationObject.keys = [];
  47216. var keys = this.getKeys();
  47217. for (var index = 0; index < keys.length; index++) {
  47218. var animationKey = keys[index];
  47219. var key = {};
  47220. key.frame = animationKey.frame;
  47221. switch (dataType) {
  47222. case Animation.ANIMATIONTYPE_FLOAT:
  47223. key.values = [animationKey.value];
  47224. break;
  47225. case Animation.ANIMATIONTYPE_QUATERNION:
  47226. case Animation.ANIMATIONTYPE_MATRIX:
  47227. case Animation.ANIMATIONTYPE_VECTOR3:
  47228. case Animation.ANIMATIONTYPE_COLOR3:
  47229. key.values = animationKey.value.asArray();
  47230. break;
  47231. }
  47232. serializationObject.keys.push(key);
  47233. }
  47234. serializationObject.ranges = [];
  47235. for (var name in this._ranges) {
  47236. var source = this._ranges[name];
  47237. if (!source) {
  47238. continue;
  47239. }
  47240. var range = {};
  47241. range.name = name;
  47242. range.from = source.from;
  47243. range.to = source.to;
  47244. serializationObject.ranges.push(range);
  47245. }
  47246. return serializationObject;
  47247. };
  47248. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  47249. get: function () {
  47250. return Animation._ANIMATIONTYPE_FLOAT;
  47251. },
  47252. enumerable: true,
  47253. configurable: true
  47254. });
  47255. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  47256. get: function () {
  47257. return Animation._ANIMATIONTYPE_VECTOR3;
  47258. },
  47259. enumerable: true,
  47260. configurable: true
  47261. });
  47262. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  47263. get: function () {
  47264. return Animation._ANIMATIONTYPE_VECTOR2;
  47265. },
  47266. enumerable: true,
  47267. configurable: true
  47268. });
  47269. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  47270. get: function () {
  47271. return Animation._ANIMATIONTYPE_SIZE;
  47272. },
  47273. enumerable: true,
  47274. configurable: true
  47275. });
  47276. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  47277. get: function () {
  47278. return Animation._ANIMATIONTYPE_QUATERNION;
  47279. },
  47280. enumerable: true,
  47281. configurable: true
  47282. });
  47283. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  47284. get: function () {
  47285. return Animation._ANIMATIONTYPE_MATRIX;
  47286. },
  47287. enumerable: true,
  47288. configurable: true
  47289. });
  47290. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  47291. get: function () {
  47292. return Animation._ANIMATIONTYPE_COLOR3;
  47293. },
  47294. enumerable: true,
  47295. configurable: true
  47296. });
  47297. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  47298. get: function () {
  47299. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  47300. },
  47301. enumerable: true,
  47302. configurable: true
  47303. });
  47304. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  47305. get: function () {
  47306. return Animation._ANIMATIONLOOPMODE_CYCLE;
  47307. },
  47308. enumerable: true,
  47309. configurable: true
  47310. });
  47311. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  47312. get: function () {
  47313. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  47314. },
  47315. enumerable: true,
  47316. configurable: true
  47317. });
  47318. Animation.Parse = function (parsedAnimation) {
  47319. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  47320. var dataType = parsedAnimation.dataType;
  47321. var keys = [];
  47322. var data;
  47323. var index;
  47324. if (parsedAnimation.enableBlending) {
  47325. animation.enableBlending = parsedAnimation.enableBlending;
  47326. }
  47327. if (parsedAnimation.blendingSpeed) {
  47328. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  47329. }
  47330. for (index = 0; index < parsedAnimation.keys.length; index++) {
  47331. var key = parsedAnimation.keys[index];
  47332. var inTangent;
  47333. var outTangent;
  47334. switch (dataType) {
  47335. case Animation.ANIMATIONTYPE_FLOAT:
  47336. data = key.values[0];
  47337. if (key.values.length >= 1) {
  47338. inTangent = key.values[1];
  47339. }
  47340. if (key.values.length >= 2) {
  47341. outTangent = key.values[2];
  47342. }
  47343. break;
  47344. case Animation.ANIMATIONTYPE_QUATERNION:
  47345. data = BABYLON.Quaternion.FromArray(key.values);
  47346. if (key.values.length >= 8) {
  47347. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  47348. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  47349. inTangent = _inTangent;
  47350. }
  47351. }
  47352. if (key.values.length >= 12) {
  47353. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  47354. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  47355. outTangent = _outTangent;
  47356. }
  47357. }
  47358. break;
  47359. case Animation.ANIMATIONTYPE_MATRIX:
  47360. data = BABYLON.Matrix.FromArray(key.values);
  47361. break;
  47362. case Animation.ANIMATIONTYPE_COLOR3:
  47363. data = BABYLON.Color3.FromArray(key.values);
  47364. break;
  47365. case Animation.ANIMATIONTYPE_VECTOR3:
  47366. default:
  47367. data = BABYLON.Vector3.FromArray(key.values);
  47368. break;
  47369. }
  47370. var keyData = {};
  47371. keyData.frame = key.frame;
  47372. keyData.value = data;
  47373. if (inTangent != undefined) {
  47374. keyData.inTangent = inTangent;
  47375. }
  47376. if (outTangent != undefined) {
  47377. keyData.outTangent = outTangent;
  47378. }
  47379. keys.push(keyData);
  47380. }
  47381. animation.setKeys(keys);
  47382. if (parsedAnimation.ranges) {
  47383. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  47384. data = parsedAnimation.ranges[index];
  47385. animation.createRange(data.name, data.from, data.to);
  47386. }
  47387. }
  47388. return animation;
  47389. };
  47390. Animation.AppendSerializedAnimations = function (source, destination) {
  47391. if (source.animations) {
  47392. destination.animations = [];
  47393. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  47394. var animation = source.animations[animationIndex];
  47395. destination.animations.push(animation.serialize());
  47396. }
  47397. }
  47398. };
  47399. Animation.AllowMatricesInterpolation = false;
  47400. // Statics
  47401. Animation._ANIMATIONTYPE_FLOAT = 0;
  47402. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  47403. Animation._ANIMATIONTYPE_QUATERNION = 2;
  47404. Animation._ANIMATIONTYPE_MATRIX = 3;
  47405. Animation._ANIMATIONTYPE_COLOR3 = 4;
  47406. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  47407. Animation._ANIMATIONTYPE_SIZE = 6;
  47408. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  47409. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  47410. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  47411. return Animation;
  47412. }());
  47413. BABYLON.Animation = Animation;
  47414. })(BABYLON || (BABYLON = {}));
  47415. //# sourceMappingURL=babylon.animation.js.map
  47416. "use strict";
  47417. var BABYLON;
  47418. (function (BABYLON) {
  47419. /**
  47420. * This class defines the direct association between an animation and a target
  47421. */
  47422. var TargetedAnimation = /** @class */ (function () {
  47423. function TargetedAnimation() {
  47424. }
  47425. return TargetedAnimation;
  47426. }());
  47427. BABYLON.TargetedAnimation = TargetedAnimation;
  47428. /**
  47429. * Use this class to create coordinated animations on multiple targets
  47430. */
  47431. var AnimationGroup = /** @class */ (function () {
  47432. function AnimationGroup(name, scene) {
  47433. if (scene === void 0) { scene = null; }
  47434. this.name = name;
  47435. this._targetedAnimations = new Array();
  47436. this._animatables = new Array();
  47437. this._from = Number.MAX_VALUE;
  47438. this._to = -Number.MAX_VALUE;
  47439. this._speedRatio = 1;
  47440. this.onAnimationEndObservable = new BABYLON.Observable();
  47441. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47442. this._scene.animationGroups.push(this);
  47443. }
  47444. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47445. /**
  47446. * Define if the animations are started
  47447. */
  47448. get: function () {
  47449. return this._isStarted;
  47450. },
  47451. enumerable: true,
  47452. configurable: true
  47453. });
  47454. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47455. /**
  47456. * Gets or sets the speed ratio to use for all animations
  47457. */
  47458. get: function () {
  47459. return this._speedRatio;
  47460. },
  47461. /**
  47462. * Gets or sets the speed ratio to use for all animations
  47463. */
  47464. set: function (value) {
  47465. if (this._speedRatio === value) {
  47466. return;
  47467. }
  47468. this._speedRatio = value;
  47469. for (var index = 0; index < this._animatables.length; index++) {
  47470. var animatable = this._animatables[index];
  47471. animatable.speedRatio = this._speedRatio;
  47472. }
  47473. },
  47474. enumerable: true,
  47475. configurable: true
  47476. });
  47477. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47478. /**
  47479. * Gets the targeted animations for this animation group
  47480. */
  47481. get: function () {
  47482. return this._targetedAnimations;
  47483. },
  47484. enumerable: true,
  47485. configurable: true
  47486. });
  47487. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47488. /**
  47489. * returning the list of animatables controlled by this animation group.
  47490. */
  47491. get: function () {
  47492. return this._animatables;
  47493. },
  47494. enumerable: true,
  47495. configurable: true
  47496. });
  47497. /**
  47498. * Add an animation (with its target) in the group
  47499. * @param animation defines the animation we want to add
  47500. * @param target defines the target of the animation
  47501. * @returns the {BABYLON.TargetedAnimation} object
  47502. */
  47503. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47504. var targetedAnimation = {
  47505. animation: animation,
  47506. target: target
  47507. };
  47508. var keys = animation.getKeys();
  47509. if (this._from > keys[0].frame) {
  47510. this._from = keys[0].frame;
  47511. }
  47512. if (this._to < keys[keys.length - 1].frame) {
  47513. this._to = keys[keys.length - 1].frame;
  47514. }
  47515. this._targetedAnimations.push(targetedAnimation);
  47516. return targetedAnimation;
  47517. };
  47518. /**
  47519. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47520. * It can add constant keys at begin or end
  47521. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47522. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47523. */
  47524. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47525. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47526. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47527. beginFrame = Math.max(beginFrame, this._from);
  47528. endFrame = Math.min(endFrame, this._to);
  47529. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47530. var targetedAnimation = this._targetedAnimations[index];
  47531. var keys = targetedAnimation.animation.getKeys();
  47532. var startKey = keys[0];
  47533. var endKey = keys[keys.length - 1];
  47534. if (startKey.frame > beginFrame) {
  47535. var newKey = {
  47536. frame: beginFrame,
  47537. value: startKey.value,
  47538. inTangent: startKey.inTangent,
  47539. outTangent: startKey.outTangent,
  47540. interpolation: startKey.interpolation
  47541. };
  47542. keys.splice(0, 0, newKey);
  47543. }
  47544. if (endKey.frame < endFrame) {
  47545. var newKey = {
  47546. frame: endFrame,
  47547. value: endKey.value,
  47548. inTangent: endKey.outTangent,
  47549. outTangent: endKey.outTangent,
  47550. interpolation: endKey.interpolation
  47551. };
  47552. keys.push(newKey);
  47553. }
  47554. }
  47555. return this;
  47556. };
  47557. /**
  47558. * Start all animations on given targets
  47559. * @param loop defines if animations must loop
  47560. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47561. */
  47562. AnimationGroup.prototype.start = function (loop, speedRatio) {
  47563. var _this = this;
  47564. if (loop === void 0) { loop = false; }
  47565. if (speedRatio === void 0) { speedRatio = 1; }
  47566. if (this._isStarted || this._targetedAnimations.length === 0) {
  47567. return this;
  47568. }
  47569. var _loop_1 = function () {
  47570. var targetedAnimation = this_1._targetedAnimations[index];
  47571. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  47572. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47573. }));
  47574. };
  47575. var this_1 = this;
  47576. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47577. _loop_1();
  47578. }
  47579. this._speedRatio = speedRatio;
  47580. this._isStarted = true;
  47581. return this;
  47582. };
  47583. /**
  47584. * Pause all animations
  47585. */
  47586. AnimationGroup.prototype.pause = function () {
  47587. if (!this._isStarted) {
  47588. return this;
  47589. }
  47590. for (var index = 0; index < this._animatables.length; index++) {
  47591. var animatable = this._animatables[index];
  47592. animatable.pause();
  47593. }
  47594. return this;
  47595. };
  47596. /**
  47597. * Play all animations to initial state
  47598. * This function will start() the animations if they were not started or will restart() them if they were paused
  47599. * @param loop defines if animations must loop
  47600. */
  47601. AnimationGroup.prototype.play = function (loop) {
  47602. if (this.isStarted) {
  47603. if (loop !== undefined) {
  47604. for (var index = 0; index < this._animatables.length; index++) {
  47605. var animatable = this._animatables[index];
  47606. animatable.loopAnimation = loop;
  47607. }
  47608. }
  47609. this.restart();
  47610. }
  47611. else {
  47612. this.start(loop, this._speedRatio);
  47613. }
  47614. return this;
  47615. };
  47616. /**
  47617. * Reset all animations to initial state
  47618. */
  47619. AnimationGroup.prototype.reset = function () {
  47620. if (!this._isStarted) {
  47621. return this;
  47622. }
  47623. for (var index = 0; index < this._animatables.length; index++) {
  47624. var animatable = this._animatables[index];
  47625. animatable.reset();
  47626. }
  47627. return this;
  47628. };
  47629. /**
  47630. * Restart animations from key 0
  47631. */
  47632. AnimationGroup.prototype.restart = function () {
  47633. if (!this._isStarted) {
  47634. return this;
  47635. }
  47636. for (var index = 0; index < this._animatables.length; index++) {
  47637. var animatable = this._animatables[index];
  47638. animatable.restart();
  47639. }
  47640. return this;
  47641. };
  47642. /**
  47643. * Stop all animations
  47644. */
  47645. AnimationGroup.prototype.stop = function () {
  47646. if (!this._isStarted) {
  47647. return this;
  47648. }
  47649. for (var index = 0; index < this._animatables.length; index++) {
  47650. var animatable = this._animatables[index];
  47651. animatable.stop();
  47652. }
  47653. this._isStarted = false;
  47654. return this;
  47655. };
  47656. /**
  47657. * Goes to a specific frame in this animation group
  47658. *
  47659. * @param frame the frame number to go to
  47660. * @return the animationGroup
  47661. */
  47662. AnimationGroup.prototype.goToFrame = function (frame) {
  47663. if (!this._isStarted) {
  47664. return this;
  47665. }
  47666. for (var index = 0; index < this._animatables.length; index++) {
  47667. var animatable = this._animatables[index];
  47668. animatable.goToFrame(frame);
  47669. }
  47670. return this;
  47671. };
  47672. /**
  47673. * Dispose all associated resources
  47674. */
  47675. AnimationGroup.prototype.dispose = function () {
  47676. this._targetedAnimations = [];
  47677. this._animatables = [];
  47678. var index = this._scene.animationGroups.indexOf(this);
  47679. if (index > -1) {
  47680. this._scene.animationGroups.splice(index, 1);
  47681. }
  47682. };
  47683. return AnimationGroup;
  47684. }());
  47685. BABYLON.AnimationGroup = AnimationGroup;
  47686. })(BABYLON || (BABYLON = {}));
  47687. //# sourceMappingURL=babylon.animationGroup.js.map
  47688. "use strict";
  47689. var BABYLON;
  47690. (function (BABYLON) {
  47691. var RuntimeAnimation = /** @class */ (function () {
  47692. /**
  47693. * Create a new RuntimeAnimation object
  47694. * @param target defines the target of the animation
  47695. * @param animation defines the source {BABYLON.Animation} object
  47696. * @param scene defines the hosting scene
  47697. */
  47698. function RuntimeAnimation(target, animation, scene) {
  47699. this.currentFrame = 0;
  47700. this._offsetsCache = {};
  47701. this._highLimitsCache = {};
  47702. this._stopped = false;
  47703. this._blendingFactor = 0;
  47704. this._targetPath = "";
  47705. this._weight = 1.0;
  47706. this._ratioOffset = 0;
  47707. this._previousDelay = 0;
  47708. this._previousRatio = 0;
  47709. this._animation = animation;
  47710. this._target = target;
  47711. this._scene = scene;
  47712. animation._runtimeAnimations.push(this);
  47713. }
  47714. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  47715. /**
  47716. * Gets the weight of the runtime animation
  47717. */
  47718. get: function () {
  47719. return this._weight;
  47720. },
  47721. enumerable: true,
  47722. configurable: true
  47723. });
  47724. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  47725. /**
  47726. * Gets the original value of the runtime animation
  47727. */
  47728. get: function () {
  47729. return this._originalValue;
  47730. },
  47731. enumerable: true,
  47732. configurable: true
  47733. });
  47734. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  47735. /**
  47736. * Gets the current value of the runtime animation
  47737. */
  47738. get: function () {
  47739. return this._currentValue;
  47740. },
  47741. enumerable: true,
  47742. configurable: true
  47743. });
  47744. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  47745. /**
  47746. * Gets the path where to store the animated value in the target
  47747. */
  47748. get: function () {
  47749. return this._targetPath;
  47750. },
  47751. enumerable: true,
  47752. configurable: true
  47753. });
  47754. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  47755. /**
  47756. * Gets the actual target of the runtime animation
  47757. */
  47758. get: function () {
  47759. return this._activeTarget;
  47760. },
  47761. enumerable: true,
  47762. configurable: true
  47763. });
  47764. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47765. get: function () {
  47766. return this._animation;
  47767. },
  47768. enumerable: true,
  47769. configurable: true
  47770. });
  47771. RuntimeAnimation.prototype.reset = function () {
  47772. this._offsetsCache = {};
  47773. this._highLimitsCache = {};
  47774. this.currentFrame = 0;
  47775. this._blendingFactor = 0;
  47776. this._originalValue = null;
  47777. };
  47778. RuntimeAnimation.prototype.isStopped = function () {
  47779. return this._stopped;
  47780. };
  47781. RuntimeAnimation.prototype.dispose = function () {
  47782. var index = this._animation.runtimeAnimations.indexOf(this);
  47783. if (index > -1) {
  47784. this._animation.runtimeAnimations.splice(index, 1);
  47785. }
  47786. };
  47787. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47788. if (typeof value === "function") {
  47789. return value();
  47790. }
  47791. return value;
  47792. };
  47793. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47794. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47795. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47796. }
  47797. this.currentFrame = currentFrame;
  47798. var keys = this._animation.getKeys();
  47799. // Try to get a hash to find the right key
  47800. 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));
  47801. if (keys[startKeyIndex].frame >= currentFrame) {
  47802. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47803. startKeyIndex--;
  47804. }
  47805. }
  47806. for (var key = startKeyIndex; key < keys.length; key++) {
  47807. var endKey = keys[key + 1];
  47808. if (endKey.frame >= currentFrame) {
  47809. var startKey = keys[key];
  47810. var startValue = this._getKeyValue(startKey.value);
  47811. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47812. return startValue;
  47813. }
  47814. var endValue = this._getKeyValue(endKey.value);
  47815. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47816. var frameDelta = endKey.frame - startKey.frame;
  47817. // gradient : percent of currentFrame between the frame inf and the frame sup
  47818. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47819. // check for easingFunction and correction of gradient
  47820. var easingFunction = this._animation.getEasingFunction();
  47821. if (easingFunction != null) {
  47822. gradient = easingFunction.ease(gradient);
  47823. }
  47824. switch (this._animation.dataType) {
  47825. // Float
  47826. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47827. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47828. switch (loopMode) {
  47829. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47830. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47831. return floatValue;
  47832. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47833. return offsetValue * repeatCount + floatValue;
  47834. }
  47835. break;
  47836. // Quaternion
  47837. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47838. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47839. switch (loopMode) {
  47840. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47841. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47842. return quatValue;
  47843. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47844. return quatValue.add(offsetValue.scale(repeatCount));
  47845. }
  47846. return quatValue;
  47847. // Vector3
  47848. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47849. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47850. switch (loopMode) {
  47851. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47852. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47853. return vec3Value;
  47854. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47855. return vec3Value.add(offsetValue.scale(repeatCount));
  47856. }
  47857. // Vector2
  47858. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47859. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47860. switch (loopMode) {
  47861. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47862. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47863. return vec2Value;
  47864. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47865. return vec2Value.add(offsetValue.scale(repeatCount));
  47866. }
  47867. // Size
  47868. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47869. switch (loopMode) {
  47870. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47871. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47872. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47873. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47874. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47875. }
  47876. // Color3
  47877. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47878. switch (loopMode) {
  47879. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47880. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47881. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47882. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47883. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47884. }
  47885. // Matrix
  47886. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47887. switch (loopMode) {
  47888. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47889. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47890. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47891. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47892. }
  47893. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47894. return startValue;
  47895. }
  47896. default:
  47897. break;
  47898. }
  47899. break;
  47900. }
  47901. }
  47902. return this._getKeyValue(keys[keys.length - 1].value);
  47903. };
  47904. /**
  47905. * Affect the interpolated value to the target
  47906. * @param currentValue defines the value computed by the animation
  47907. * @param weight defines the weight to apply to this value
  47908. */
  47909. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  47910. if (weight === void 0) { weight = 1.0; }
  47911. // Set value
  47912. var path;
  47913. var destination;
  47914. var targetPropertyPath = this._animation.targetPropertyPath;
  47915. if (targetPropertyPath.length > 1) {
  47916. var property = this._target[targetPropertyPath[0]];
  47917. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47918. property = property[targetPropertyPath[index]];
  47919. }
  47920. path = targetPropertyPath[targetPropertyPath.length - 1];
  47921. destination = property;
  47922. }
  47923. else {
  47924. path = targetPropertyPath[0];
  47925. destination = this._target;
  47926. }
  47927. this._targetPath = path;
  47928. this._activeTarget = destination;
  47929. this._weight = weight;
  47930. // Blending
  47931. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47932. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47933. if (enableBlending && this._blendingFactor <= 1.0) {
  47934. if (!this._originalBlendValue) {
  47935. var originalValue = destination[path];
  47936. if (originalValue.clone) {
  47937. this._originalBlendValue = originalValue.clone();
  47938. }
  47939. else {
  47940. this._originalBlendValue = originalValue;
  47941. }
  47942. }
  47943. }
  47944. if (weight !== -1.0) {
  47945. if (!this._originalValue) {
  47946. var originalValue = void 0;
  47947. if (destination.getRestPose) {
  47948. originalValue = destination.getRestPose();
  47949. }
  47950. else {
  47951. originalValue = destination[path];
  47952. }
  47953. if (originalValue.clone) {
  47954. this._originalValue = originalValue.clone();
  47955. }
  47956. else {
  47957. this._originalValue = originalValue;
  47958. }
  47959. }
  47960. }
  47961. if (enableBlending && this._blendingFactor <= 1.0) {
  47962. if (this._originalBlendValue.prototype) {
  47963. if (this._originalBlendValue.prototype.Lerp) {
  47964. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47965. }
  47966. else {
  47967. this._currentValue = currentValue;
  47968. }
  47969. }
  47970. else if (this._originalBlendValue.m) {
  47971. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47972. }
  47973. else {
  47974. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47975. }
  47976. this._blendingFactor += blendingSpeed;
  47977. }
  47978. else {
  47979. this._currentValue = currentValue;
  47980. }
  47981. if (weight !== -1.0) {
  47982. this._scene._registerTargetForLateAnimationBinding(this);
  47983. }
  47984. else {
  47985. destination[path] = this._currentValue;
  47986. }
  47987. if (this._target.markAsDirty) {
  47988. this._target.markAsDirty(this._animation.targetProperty);
  47989. }
  47990. };
  47991. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47992. if (this._target && this._target.animationPropertiesOverride) {
  47993. return this._target.animationPropertiesOverride.loopMode;
  47994. }
  47995. return this._animation.loopMode;
  47996. };
  47997. /**
  47998. * Move the current animation to a given frame
  47999. * @param frame defines the frame to move to
  48000. */
  48001. RuntimeAnimation.prototype.goToFrame = function (frame) {
  48002. var keys = this._animation.getKeys();
  48003. if (frame < keys[0].frame) {
  48004. frame = keys[0].frame;
  48005. }
  48006. else if (frame > keys[keys.length - 1].frame) {
  48007. frame = keys[keys.length - 1].frame;
  48008. }
  48009. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  48010. this.setValue(currentValue, -1);
  48011. };
  48012. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  48013. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  48014. this._ratioOffset = this._previousRatio - newRatio;
  48015. };
  48016. /**
  48017. * Execute the current animation
  48018. * @param delay defines the delay to add to the current frame
  48019. * @param from defines the lower bound of the animation range
  48020. * @param to defines the upper bound of the animation range
  48021. * @param loop defines if the current animation must loop
  48022. * @param speedRatio defines the current speed ratio
  48023. * @param weight defines the weight of the animation (default is -1 so no weight)
  48024. * @returns a boolean indicating if the animation has ended
  48025. */
  48026. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  48027. if (weight === void 0) { weight = -1.0; }
  48028. var targetPropertyPath = this._animation.targetPropertyPath;
  48029. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  48030. this._stopped = true;
  48031. return false;
  48032. }
  48033. var returnValue = true;
  48034. var keys = this._animation.getKeys();
  48035. // Adding a start key at frame 0 if missing
  48036. if (keys[0].frame !== 0) {
  48037. var newKey = { frame: 0, value: keys[0].value };
  48038. keys.splice(0, 0, newKey);
  48039. }
  48040. // Check limits
  48041. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  48042. from = keys[0].frame;
  48043. }
  48044. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  48045. to = keys[keys.length - 1].frame;
  48046. }
  48047. //to and from cannot be the same key
  48048. if (from === to) {
  48049. if (from > keys[0].frame) {
  48050. from--;
  48051. }
  48052. else if (to < keys[keys.length - 1].frame) {
  48053. to++;
  48054. }
  48055. }
  48056. // Compute ratio
  48057. var range = to - from;
  48058. var offsetValue;
  48059. // ratio represents the frame delta between from and to
  48060. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  48061. var highLimitValue = 0;
  48062. this._previousDelay = delay;
  48063. this._previousRatio = ratio;
  48064. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  48065. returnValue = false;
  48066. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  48067. }
  48068. else {
  48069. // Get max value if required
  48070. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  48071. var keyOffset = to.toString() + from.toString();
  48072. if (!this._offsetsCache[keyOffset]) {
  48073. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48074. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48075. switch (this._animation.dataType) {
  48076. // Float
  48077. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48078. this._offsetsCache[keyOffset] = toValue - fromValue;
  48079. break;
  48080. // Quaternion
  48081. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48082. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48083. break;
  48084. // Vector3
  48085. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48086. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48087. // Vector2
  48088. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48089. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48090. // Size
  48091. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48092. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48093. // Color3
  48094. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48095. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48096. default:
  48097. break;
  48098. }
  48099. this._highLimitsCache[keyOffset] = toValue;
  48100. }
  48101. highLimitValue = this._highLimitsCache[keyOffset];
  48102. offsetValue = this._offsetsCache[keyOffset];
  48103. }
  48104. }
  48105. if (offsetValue === undefined) {
  48106. switch (this._animation.dataType) {
  48107. // Float
  48108. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48109. offsetValue = 0;
  48110. break;
  48111. // Quaternion
  48112. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48113. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  48114. break;
  48115. // Vector3
  48116. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48117. offsetValue = BABYLON.Vector3.Zero();
  48118. break;
  48119. // Vector2
  48120. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48121. offsetValue = BABYLON.Vector2.Zero();
  48122. break;
  48123. // Size
  48124. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48125. offsetValue = BABYLON.Size.Zero();
  48126. break;
  48127. // Color3
  48128. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48129. offsetValue = BABYLON.Color3.Black();
  48130. }
  48131. }
  48132. // Compute value
  48133. var repeatCount = (ratio / range) >> 0;
  48134. var currentFrame = returnValue ? from + ratio % range : to;
  48135. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  48136. // Set value
  48137. this.setValue(currentValue, weight);
  48138. // Check events
  48139. var events = this._animation.getEvents();
  48140. for (var index = 0; index < events.length; index++) {
  48141. // Make sure current frame has passed event frame and that event frame is within the current range
  48142. // Also, handle both forward and reverse animations
  48143. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  48144. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  48145. var event = events[index];
  48146. if (!event.isDone) {
  48147. // If event should be done only once, remove it.
  48148. if (event.onlyOnce) {
  48149. events.splice(index, 1);
  48150. index--;
  48151. }
  48152. event.isDone = true;
  48153. event.action();
  48154. } // Don't do anything if the event has already be done.
  48155. }
  48156. else if (events[index].isDone && !events[index].onlyOnce) {
  48157. // reset event, the animation is looping
  48158. events[index].isDone = false;
  48159. }
  48160. }
  48161. if (!returnValue) {
  48162. this._stopped = true;
  48163. }
  48164. return returnValue;
  48165. };
  48166. return RuntimeAnimation;
  48167. }());
  48168. BABYLON.RuntimeAnimation = RuntimeAnimation;
  48169. })(BABYLON || (BABYLON = {}));
  48170. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  48171. "use strict";
  48172. var BABYLON;
  48173. (function (BABYLON) {
  48174. var Animatable = /** @class */ (function () {
  48175. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  48176. if (fromFrame === void 0) { fromFrame = 0; }
  48177. if (toFrame === void 0) { toFrame = 100; }
  48178. if (loopAnimation === void 0) { loopAnimation = false; }
  48179. if (speedRatio === void 0) { speedRatio = 1.0; }
  48180. this.target = target;
  48181. this.fromFrame = fromFrame;
  48182. this.toFrame = toFrame;
  48183. this.loopAnimation = loopAnimation;
  48184. this.onAnimationEnd = onAnimationEnd;
  48185. this._localDelayOffset = null;
  48186. this._pausedDelay = null;
  48187. this._runtimeAnimations = new Array();
  48188. this._paused = false;
  48189. this._speedRatio = 1;
  48190. this._weight = -1.0;
  48191. this.animationStarted = false;
  48192. if (animations) {
  48193. this.appendAnimations(target, animations);
  48194. }
  48195. this._speedRatio = speedRatio;
  48196. this._scene = scene;
  48197. scene._activeAnimatables.push(this);
  48198. }
  48199. Object.defineProperty(Animatable.prototype, "weight", {
  48200. /**
  48201. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  48202. */
  48203. get: function () {
  48204. return this._weight;
  48205. },
  48206. set: function (value) {
  48207. if (value === -1) {
  48208. this._weight = -1;
  48209. return;
  48210. }
  48211. // Else weight must be in [0, 1] range
  48212. this._weight = Math.min(Math.max(value, 0), 1.0);
  48213. },
  48214. enumerable: true,
  48215. configurable: true
  48216. });
  48217. Object.defineProperty(Animatable.prototype, "speedRatio", {
  48218. /**
  48219. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  48220. */
  48221. get: function () {
  48222. return this._speedRatio;
  48223. },
  48224. set: function (value) {
  48225. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  48226. var animation = this._runtimeAnimations[index];
  48227. animation._prepareForSpeedRatioChange(value);
  48228. }
  48229. this._speedRatio = value;
  48230. },
  48231. enumerable: true,
  48232. configurable: true
  48233. });
  48234. // Methods
  48235. Animatable.prototype.getAnimations = function () {
  48236. return this._runtimeAnimations;
  48237. };
  48238. Animatable.prototype.appendAnimations = function (target, animations) {
  48239. for (var index = 0; index < animations.length; index++) {
  48240. var animation = animations[index];
  48241. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene));
  48242. }
  48243. };
  48244. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  48245. var runtimeAnimations = this._runtimeAnimations;
  48246. for (var index = 0; index < runtimeAnimations.length; index++) {
  48247. if (runtimeAnimations[index].animation.targetProperty === property) {
  48248. return runtimeAnimations[index].animation;
  48249. }
  48250. }
  48251. return null;
  48252. };
  48253. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  48254. var runtimeAnimations = this._runtimeAnimations;
  48255. for (var index = 0; index < runtimeAnimations.length; index++) {
  48256. if (runtimeAnimations[index].animation.targetProperty === property) {
  48257. return runtimeAnimations[index];
  48258. }
  48259. }
  48260. return null;
  48261. };
  48262. Animatable.prototype.reset = function () {
  48263. var runtimeAnimations = this._runtimeAnimations;
  48264. for (var index = 0; index < runtimeAnimations.length; index++) {
  48265. runtimeAnimations[index].reset();
  48266. }
  48267. // Reset to original value
  48268. for (index = 0; index < runtimeAnimations.length; index++) {
  48269. var animation = runtimeAnimations[index];
  48270. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  48271. }
  48272. this._localDelayOffset = null;
  48273. this._pausedDelay = null;
  48274. };
  48275. Animatable.prototype.enableBlending = function (blendingSpeed) {
  48276. var runtimeAnimations = this._runtimeAnimations;
  48277. for (var index = 0; index < runtimeAnimations.length; index++) {
  48278. runtimeAnimations[index].animation.enableBlending = true;
  48279. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  48280. }
  48281. };
  48282. Animatable.prototype.disableBlending = function () {
  48283. var runtimeAnimations = this._runtimeAnimations;
  48284. for (var index = 0; index < runtimeAnimations.length; index++) {
  48285. runtimeAnimations[index].animation.enableBlending = false;
  48286. }
  48287. };
  48288. Animatable.prototype.goToFrame = function (frame) {
  48289. var runtimeAnimations = this._runtimeAnimations;
  48290. if (runtimeAnimations[0]) {
  48291. var fps = runtimeAnimations[0].animation.framePerSecond;
  48292. var currentFrame = runtimeAnimations[0].currentFrame;
  48293. var adjustTime = frame - currentFrame;
  48294. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  48295. if (this._localDelayOffset === null) {
  48296. this._localDelayOffset = 0;
  48297. }
  48298. this._localDelayOffset -= delay;
  48299. }
  48300. for (var index = 0; index < runtimeAnimations.length; index++) {
  48301. runtimeAnimations[index].goToFrame(frame);
  48302. }
  48303. };
  48304. Animatable.prototype.pause = function () {
  48305. if (this._paused) {
  48306. return;
  48307. }
  48308. this._paused = true;
  48309. };
  48310. Animatable.prototype.restart = function () {
  48311. this._paused = false;
  48312. };
  48313. Animatable.prototype.stop = function (animationName) {
  48314. if (animationName) {
  48315. var idx = this._scene._activeAnimatables.indexOf(this);
  48316. if (idx > -1) {
  48317. var runtimeAnimations = this._runtimeAnimations;
  48318. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  48319. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  48320. continue;
  48321. }
  48322. runtimeAnimations[index].dispose();
  48323. runtimeAnimations.splice(index, 1);
  48324. }
  48325. if (runtimeAnimations.length == 0) {
  48326. this._scene._activeAnimatables.splice(idx, 1);
  48327. if (this.onAnimationEnd) {
  48328. this.onAnimationEnd();
  48329. }
  48330. }
  48331. }
  48332. }
  48333. else {
  48334. var index = this._scene._activeAnimatables.indexOf(this);
  48335. if (index > -1) {
  48336. this._scene._activeAnimatables.splice(index, 1);
  48337. var runtimeAnimations = this._runtimeAnimations;
  48338. for (var index = 0; index < runtimeAnimations.length; index++) {
  48339. runtimeAnimations[index].dispose();
  48340. }
  48341. if (this.onAnimationEnd) {
  48342. this.onAnimationEnd();
  48343. }
  48344. }
  48345. }
  48346. };
  48347. Animatable.prototype._animate = function (delay) {
  48348. if (this._paused) {
  48349. this.animationStarted = false;
  48350. if (this._pausedDelay === null) {
  48351. this._pausedDelay = delay;
  48352. }
  48353. return true;
  48354. }
  48355. if (this._localDelayOffset === null) {
  48356. this._localDelayOffset = delay;
  48357. this._pausedDelay = null;
  48358. }
  48359. else if (this._pausedDelay !== null) {
  48360. this._localDelayOffset += delay - this._pausedDelay;
  48361. this._pausedDelay = null;
  48362. }
  48363. if (this._weight === 0) {
  48364. return true;
  48365. }
  48366. // Animating
  48367. var running = false;
  48368. var runtimeAnimations = this._runtimeAnimations;
  48369. var index;
  48370. for (index = 0; index < runtimeAnimations.length; index++) {
  48371. var animation = runtimeAnimations[index];
  48372. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  48373. running = running || isRunning;
  48374. }
  48375. this.animationStarted = running;
  48376. if (!running) {
  48377. // Remove from active animatables
  48378. index = this._scene._activeAnimatables.indexOf(this);
  48379. this._scene._activeAnimatables.splice(index, 1);
  48380. // Dispose all runtime animations
  48381. for (index = 0; index < runtimeAnimations.length; index++) {
  48382. runtimeAnimations[index].dispose();
  48383. }
  48384. }
  48385. if (!running && this.onAnimationEnd) {
  48386. this.onAnimationEnd();
  48387. this.onAnimationEnd = null;
  48388. }
  48389. return running;
  48390. };
  48391. return Animatable;
  48392. }());
  48393. BABYLON.Animatable = Animatable;
  48394. })(BABYLON || (BABYLON = {}));
  48395. //# sourceMappingURL=babylon.animatable.js.map
  48396. "use strict";
  48397. var BABYLON;
  48398. (function (BABYLON) {
  48399. var EasingFunction = /** @class */ (function () {
  48400. function EasingFunction() {
  48401. // Properties
  48402. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  48403. }
  48404. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  48405. get: function () {
  48406. return EasingFunction._EASINGMODE_EASEIN;
  48407. },
  48408. enumerable: true,
  48409. configurable: true
  48410. });
  48411. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  48412. get: function () {
  48413. return EasingFunction._EASINGMODE_EASEOUT;
  48414. },
  48415. enumerable: true,
  48416. configurable: true
  48417. });
  48418. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  48419. get: function () {
  48420. return EasingFunction._EASINGMODE_EASEINOUT;
  48421. },
  48422. enumerable: true,
  48423. configurable: true
  48424. });
  48425. EasingFunction.prototype.setEasingMode = function (easingMode) {
  48426. var n = Math.min(Math.max(easingMode, 0), 2);
  48427. this._easingMode = n;
  48428. };
  48429. EasingFunction.prototype.getEasingMode = function () {
  48430. return this._easingMode;
  48431. };
  48432. EasingFunction.prototype.easeInCore = function (gradient) {
  48433. throw new Error('You must implement this method');
  48434. };
  48435. EasingFunction.prototype.ease = function (gradient) {
  48436. switch (this._easingMode) {
  48437. case EasingFunction.EASINGMODE_EASEIN:
  48438. return this.easeInCore(gradient);
  48439. case EasingFunction.EASINGMODE_EASEOUT:
  48440. return (1 - this.easeInCore(1 - gradient));
  48441. }
  48442. if (gradient >= 0.5) {
  48443. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  48444. }
  48445. return (this.easeInCore(gradient * 2) * 0.5);
  48446. };
  48447. //Statics
  48448. EasingFunction._EASINGMODE_EASEIN = 0;
  48449. EasingFunction._EASINGMODE_EASEOUT = 1;
  48450. EasingFunction._EASINGMODE_EASEINOUT = 2;
  48451. return EasingFunction;
  48452. }());
  48453. BABYLON.EasingFunction = EasingFunction;
  48454. var CircleEase = /** @class */ (function (_super) {
  48455. __extends(CircleEase, _super);
  48456. function CircleEase() {
  48457. return _super !== null && _super.apply(this, arguments) || this;
  48458. }
  48459. CircleEase.prototype.easeInCore = function (gradient) {
  48460. gradient = Math.max(0, Math.min(1, gradient));
  48461. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  48462. };
  48463. return CircleEase;
  48464. }(EasingFunction));
  48465. BABYLON.CircleEase = CircleEase;
  48466. var BackEase = /** @class */ (function (_super) {
  48467. __extends(BackEase, _super);
  48468. function BackEase(amplitude) {
  48469. if (amplitude === void 0) { amplitude = 1; }
  48470. var _this = _super.call(this) || this;
  48471. _this.amplitude = amplitude;
  48472. return _this;
  48473. }
  48474. BackEase.prototype.easeInCore = function (gradient) {
  48475. var num = Math.max(0, this.amplitude);
  48476. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  48477. };
  48478. return BackEase;
  48479. }(EasingFunction));
  48480. BABYLON.BackEase = BackEase;
  48481. var BounceEase = /** @class */ (function (_super) {
  48482. __extends(BounceEase, _super);
  48483. function BounceEase(bounces, bounciness) {
  48484. if (bounces === void 0) { bounces = 3; }
  48485. if (bounciness === void 0) { bounciness = 2; }
  48486. var _this = _super.call(this) || this;
  48487. _this.bounces = bounces;
  48488. _this.bounciness = bounciness;
  48489. return _this;
  48490. }
  48491. BounceEase.prototype.easeInCore = function (gradient) {
  48492. var y = Math.max(0.0, this.bounces);
  48493. var bounciness = this.bounciness;
  48494. if (bounciness <= 1.0) {
  48495. bounciness = 1.001;
  48496. }
  48497. var num9 = Math.pow(bounciness, y);
  48498. var num5 = 1.0 - bounciness;
  48499. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  48500. var num15 = gradient * num4;
  48501. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  48502. var num3 = Math.floor(num65);
  48503. var num13 = num3 + 1.0;
  48504. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  48505. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  48506. var num7 = (num8 + num12) * 0.5;
  48507. var num6 = gradient - num7;
  48508. var num2 = num7 - num8;
  48509. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  48510. };
  48511. return BounceEase;
  48512. }(EasingFunction));
  48513. BABYLON.BounceEase = BounceEase;
  48514. var CubicEase = /** @class */ (function (_super) {
  48515. __extends(CubicEase, _super);
  48516. function CubicEase() {
  48517. return _super !== null && _super.apply(this, arguments) || this;
  48518. }
  48519. CubicEase.prototype.easeInCore = function (gradient) {
  48520. return (gradient * gradient * gradient);
  48521. };
  48522. return CubicEase;
  48523. }(EasingFunction));
  48524. BABYLON.CubicEase = CubicEase;
  48525. var ElasticEase = /** @class */ (function (_super) {
  48526. __extends(ElasticEase, _super);
  48527. function ElasticEase(oscillations, springiness) {
  48528. if (oscillations === void 0) { oscillations = 3; }
  48529. if (springiness === void 0) { springiness = 3; }
  48530. var _this = _super.call(this) || this;
  48531. _this.oscillations = oscillations;
  48532. _this.springiness = springiness;
  48533. return _this;
  48534. }
  48535. ElasticEase.prototype.easeInCore = function (gradient) {
  48536. var num2;
  48537. var num3 = Math.max(0.0, this.oscillations);
  48538. var num = Math.max(0.0, this.springiness);
  48539. if (num == 0) {
  48540. num2 = gradient;
  48541. }
  48542. else {
  48543. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  48544. }
  48545. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  48546. };
  48547. return ElasticEase;
  48548. }(EasingFunction));
  48549. BABYLON.ElasticEase = ElasticEase;
  48550. var ExponentialEase = /** @class */ (function (_super) {
  48551. __extends(ExponentialEase, _super);
  48552. function ExponentialEase(exponent) {
  48553. if (exponent === void 0) { exponent = 2; }
  48554. var _this = _super.call(this) || this;
  48555. _this.exponent = exponent;
  48556. return _this;
  48557. }
  48558. ExponentialEase.prototype.easeInCore = function (gradient) {
  48559. if (this.exponent <= 0) {
  48560. return gradient;
  48561. }
  48562. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  48563. };
  48564. return ExponentialEase;
  48565. }(EasingFunction));
  48566. BABYLON.ExponentialEase = ExponentialEase;
  48567. var PowerEase = /** @class */ (function (_super) {
  48568. __extends(PowerEase, _super);
  48569. function PowerEase(power) {
  48570. if (power === void 0) { power = 2; }
  48571. var _this = _super.call(this) || this;
  48572. _this.power = power;
  48573. return _this;
  48574. }
  48575. PowerEase.prototype.easeInCore = function (gradient) {
  48576. var y = Math.max(0.0, this.power);
  48577. return Math.pow(gradient, y);
  48578. };
  48579. return PowerEase;
  48580. }(EasingFunction));
  48581. BABYLON.PowerEase = PowerEase;
  48582. var QuadraticEase = /** @class */ (function (_super) {
  48583. __extends(QuadraticEase, _super);
  48584. function QuadraticEase() {
  48585. return _super !== null && _super.apply(this, arguments) || this;
  48586. }
  48587. QuadraticEase.prototype.easeInCore = function (gradient) {
  48588. return (gradient * gradient);
  48589. };
  48590. return QuadraticEase;
  48591. }(EasingFunction));
  48592. BABYLON.QuadraticEase = QuadraticEase;
  48593. var QuarticEase = /** @class */ (function (_super) {
  48594. __extends(QuarticEase, _super);
  48595. function QuarticEase() {
  48596. return _super !== null && _super.apply(this, arguments) || this;
  48597. }
  48598. QuarticEase.prototype.easeInCore = function (gradient) {
  48599. return (gradient * gradient * gradient * gradient);
  48600. };
  48601. return QuarticEase;
  48602. }(EasingFunction));
  48603. BABYLON.QuarticEase = QuarticEase;
  48604. var QuinticEase = /** @class */ (function (_super) {
  48605. __extends(QuinticEase, _super);
  48606. function QuinticEase() {
  48607. return _super !== null && _super.apply(this, arguments) || this;
  48608. }
  48609. QuinticEase.prototype.easeInCore = function (gradient) {
  48610. return (gradient * gradient * gradient * gradient * gradient);
  48611. };
  48612. return QuinticEase;
  48613. }(EasingFunction));
  48614. BABYLON.QuinticEase = QuinticEase;
  48615. var SineEase = /** @class */ (function (_super) {
  48616. __extends(SineEase, _super);
  48617. function SineEase() {
  48618. return _super !== null && _super.apply(this, arguments) || this;
  48619. }
  48620. SineEase.prototype.easeInCore = function (gradient) {
  48621. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48622. };
  48623. return SineEase;
  48624. }(EasingFunction));
  48625. BABYLON.SineEase = SineEase;
  48626. var BezierCurveEase = /** @class */ (function (_super) {
  48627. __extends(BezierCurveEase, _super);
  48628. function BezierCurveEase(x1, y1, x2, y2) {
  48629. if (x1 === void 0) { x1 = 0; }
  48630. if (y1 === void 0) { y1 = 0; }
  48631. if (x2 === void 0) { x2 = 1; }
  48632. if (y2 === void 0) { y2 = 1; }
  48633. var _this = _super.call(this) || this;
  48634. _this.x1 = x1;
  48635. _this.y1 = y1;
  48636. _this.x2 = x2;
  48637. _this.y2 = y2;
  48638. return _this;
  48639. }
  48640. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48641. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48642. };
  48643. return BezierCurveEase;
  48644. }(EasingFunction));
  48645. BABYLON.BezierCurveEase = BezierCurveEase;
  48646. })(BABYLON || (BABYLON = {}));
  48647. //# sourceMappingURL=babylon.easing.js.map
  48648. "use strict";
  48649. var BABYLON;
  48650. (function (BABYLON) {
  48651. var Condition = /** @class */ (function () {
  48652. function Condition(actionManager) {
  48653. this._actionManager = actionManager;
  48654. }
  48655. Condition.prototype.isValid = function () {
  48656. return true;
  48657. };
  48658. Condition.prototype._getProperty = function (propertyPath) {
  48659. return this._actionManager._getProperty(propertyPath);
  48660. };
  48661. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48662. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48663. };
  48664. Condition.prototype.serialize = function () {
  48665. };
  48666. Condition.prototype._serialize = function (serializedCondition) {
  48667. return {
  48668. type: 2,
  48669. children: [],
  48670. name: serializedCondition.name,
  48671. properties: serializedCondition.properties
  48672. };
  48673. };
  48674. return Condition;
  48675. }());
  48676. BABYLON.Condition = Condition;
  48677. var ValueCondition = /** @class */ (function (_super) {
  48678. __extends(ValueCondition, _super);
  48679. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48680. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48681. var _this = _super.call(this, actionManager) || this;
  48682. _this.propertyPath = propertyPath;
  48683. _this.value = value;
  48684. _this.operator = operator;
  48685. _this._target = target;
  48686. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48687. _this._property = _this._getProperty(_this.propertyPath);
  48688. return _this;
  48689. }
  48690. Object.defineProperty(ValueCondition, "IsEqual", {
  48691. get: function () {
  48692. return ValueCondition._IsEqual;
  48693. },
  48694. enumerable: true,
  48695. configurable: true
  48696. });
  48697. Object.defineProperty(ValueCondition, "IsDifferent", {
  48698. get: function () {
  48699. return ValueCondition._IsDifferent;
  48700. },
  48701. enumerable: true,
  48702. configurable: true
  48703. });
  48704. Object.defineProperty(ValueCondition, "IsGreater", {
  48705. get: function () {
  48706. return ValueCondition._IsGreater;
  48707. },
  48708. enumerable: true,
  48709. configurable: true
  48710. });
  48711. Object.defineProperty(ValueCondition, "IsLesser", {
  48712. get: function () {
  48713. return ValueCondition._IsLesser;
  48714. },
  48715. enumerable: true,
  48716. configurable: true
  48717. });
  48718. // Methods
  48719. ValueCondition.prototype.isValid = function () {
  48720. switch (this.operator) {
  48721. case ValueCondition.IsGreater:
  48722. return this._effectiveTarget[this._property] > this.value;
  48723. case ValueCondition.IsLesser:
  48724. return this._effectiveTarget[this._property] < this.value;
  48725. case ValueCondition.IsEqual:
  48726. case ValueCondition.IsDifferent:
  48727. var check;
  48728. if (this.value.equals) {
  48729. check = this.value.equals(this._effectiveTarget[this._property]);
  48730. }
  48731. else {
  48732. check = this.value === this._effectiveTarget[this._property];
  48733. }
  48734. return this.operator === ValueCondition.IsEqual ? check : !check;
  48735. }
  48736. return false;
  48737. };
  48738. ValueCondition.prototype.serialize = function () {
  48739. return this._serialize({
  48740. name: "ValueCondition",
  48741. properties: [
  48742. BABYLON.Action._GetTargetProperty(this._target),
  48743. { name: "propertyPath", value: this.propertyPath },
  48744. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48745. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48746. ]
  48747. });
  48748. };
  48749. ValueCondition.GetOperatorName = function (operator) {
  48750. switch (operator) {
  48751. case ValueCondition._IsEqual: return "IsEqual";
  48752. case ValueCondition._IsDifferent: return "IsDifferent";
  48753. case ValueCondition._IsGreater: return "IsGreater";
  48754. case ValueCondition._IsLesser: return "IsLesser";
  48755. default: return "";
  48756. }
  48757. };
  48758. // Statics
  48759. ValueCondition._IsEqual = 0;
  48760. ValueCondition._IsDifferent = 1;
  48761. ValueCondition._IsGreater = 2;
  48762. ValueCondition._IsLesser = 3;
  48763. return ValueCondition;
  48764. }(Condition));
  48765. BABYLON.ValueCondition = ValueCondition;
  48766. var PredicateCondition = /** @class */ (function (_super) {
  48767. __extends(PredicateCondition, _super);
  48768. function PredicateCondition(actionManager, predicate) {
  48769. var _this = _super.call(this, actionManager) || this;
  48770. _this.predicate = predicate;
  48771. return _this;
  48772. }
  48773. PredicateCondition.prototype.isValid = function () {
  48774. return this.predicate();
  48775. };
  48776. return PredicateCondition;
  48777. }(Condition));
  48778. BABYLON.PredicateCondition = PredicateCondition;
  48779. var StateCondition = /** @class */ (function (_super) {
  48780. __extends(StateCondition, _super);
  48781. function StateCondition(actionManager, target, value) {
  48782. var _this = _super.call(this, actionManager) || this;
  48783. _this.value = value;
  48784. _this._target = target;
  48785. return _this;
  48786. }
  48787. // Methods
  48788. StateCondition.prototype.isValid = function () {
  48789. return this._target.state === this.value;
  48790. };
  48791. StateCondition.prototype.serialize = function () {
  48792. return this._serialize({
  48793. name: "StateCondition",
  48794. properties: [
  48795. BABYLON.Action._GetTargetProperty(this._target),
  48796. { name: "value", value: this.value }
  48797. ]
  48798. });
  48799. };
  48800. return StateCondition;
  48801. }(Condition));
  48802. BABYLON.StateCondition = StateCondition;
  48803. })(BABYLON || (BABYLON = {}));
  48804. //# sourceMappingURL=babylon.condition.js.map
  48805. "use strict";
  48806. var BABYLON;
  48807. (function (BABYLON) {
  48808. var Action = /** @class */ (function () {
  48809. function Action(triggerOptions, condition) {
  48810. this.triggerOptions = triggerOptions;
  48811. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48812. if (triggerOptions.parameter) {
  48813. this.trigger = triggerOptions.trigger;
  48814. this._triggerParameter = triggerOptions.parameter;
  48815. }
  48816. else {
  48817. this.trigger = triggerOptions;
  48818. }
  48819. this._nextActiveAction = this;
  48820. this._condition = condition;
  48821. }
  48822. // Methods
  48823. Action.prototype._prepare = function () {
  48824. };
  48825. Action.prototype.getTriggerParameter = function () {
  48826. return this._triggerParameter;
  48827. };
  48828. Action.prototype._executeCurrent = function (evt) {
  48829. if (this._nextActiveAction._condition) {
  48830. var condition = this._nextActiveAction._condition;
  48831. var currentRenderId = this._actionManager.getScene().getRenderId();
  48832. // We cache the current evaluation for the current frame
  48833. if (condition._evaluationId === currentRenderId) {
  48834. if (!condition._currentResult) {
  48835. return;
  48836. }
  48837. }
  48838. else {
  48839. condition._evaluationId = currentRenderId;
  48840. if (!condition.isValid()) {
  48841. condition._currentResult = false;
  48842. return;
  48843. }
  48844. condition._currentResult = true;
  48845. }
  48846. }
  48847. this.onBeforeExecuteObservable.notifyObservers(this);
  48848. this._nextActiveAction.execute(evt);
  48849. this.skipToNextActiveAction();
  48850. };
  48851. Action.prototype.execute = function (evt) {
  48852. };
  48853. Action.prototype.skipToNextActiveAction = function () {
  48854. if (this._nextActiveAction._child) {
  48855. if (!this._nextActiveAction._child._actionManager) {
  48856. this._nextActiveAction._child._actionManager = this._actionManager;
  48857. }
  48858. this._nextActiveAction = this._nextActiveAction._child;
  48859. }
  48860. else {
  48861. this._nextActiveAction = this;
  48862. }
  48863. };
  48864. Action.prototype.then = function (action) {
  48865. this._child = action;
  48866. action._actionManager = this._actionManager;
  48867. action._prepare();
  48868. return action;
  48869. };
  48870. Action.prototype._getProperty = function (propertyPath) {
  48871. return this._actionManager._getProperty(propertyPath);
  48872. };
  48873. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48874. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48875. };
  48876. Action.prototype.serialize = function (parent) {
  48877. };
  48878. // Called by BABYLON.Action objects in serialize(...). Internal use
  48879. Action.prototype._serialize = function (serializedAction, parent) {
  48880. var serializationObject = {
  48881. type: 1,
  48882. children: [],
  48883. name: serializedAction.name,
  48884. properties: serializedAction.properties || []
  48885. };
  48886. // Serialize child
  48887. if (this._child) {
  48888. this._child.serialize(serializationObject);
  48889. }
  48890. // Check if "this" has a condition
  48891. if (this._condition) {
  48892. var serializedCondition = this._condition.serialize();
  48893. serializedCondition.children.push(serializationObject);
  48894. if (parent) {
  48895. parent.children.push(serializedCondition);
  48896. }
  48897. return serializedCondition;
  48898. }
  48899. if (parent) {
  48900. parent.children.push(serializationObject);
  48901. }
  48902. return serializationObject;
  48903. };
  48904. Action._SerializeValueAsString = function (value) {
  48905. if (typeof value === "number") {
  48906. return value.toString();
  48907. }
  48908. if (typeof value === "boolean") {
  48909. return value ? "true" : "false";
  48910. }
  48911. if (value instanceof BABYLON.Vector2) {
  48912. return value.x + ", " + value.y;
  48913. }
  48914. if (value instanceof BABYLON.Vector3) {
  48915. return value.x + ", " + value.y + ", " + value.z;
  48916. }
  48917. if (value instanceof BABYLON.Color3) {
  48918. return value.r + ", " + value.g + ", " + value.b;
  48919. }
  48920. if (value instanceof BABYLON.Color4) {
  48921. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48922. }
  48923. return value; // string
  48924. };
  48925. Action._GetTargetProperty = function (target) {
  48926. return {
  48927. name: "target",
  48928. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48929. : target instanceof BABYLON.Light ? "LightProperties"
  48930. : target instanceof BABYLON.Camera ? "CameraProperties"
  48931. : "SceneProperties",
  48932. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48933. };
  48934. };
  48935. return Action;
  48936. }());
  48937. BABYLON.Action = Action;
  48938. })(BABYLON || (BABYLON = {}));
  48939. //# sourceMappingURL=babylon.action.js.map
  48940. "use strict";
  48941. var BABYLON;
  48942. (function (BABYLON) {
  48943. /**
  48944. * ActionEvent is the event beint sent when an action is triggered.
  48945. */
  48946. var ActionEvent = /** @class */ (function () {
  48947. /**
  48948. * @param source The mesh or sprite that triggered the action.
  48949. * @param pointerX The X mouse cursor position at the time of the event
  48950. * @param pointerY The Y mouse cursor position at the time of the event
  48951. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48952. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48953. */
  48954. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48955. this.source = source;
  48956. this.pointerX = pointerX;
  48957. this.pointerY = pointerY;
  48958. this.meshUnderPointer = meshUnderPointer;
  48959. this.sourceEvent = sourceEvent;
  48960. this.additionalData = additionalData;
  48961. }
  48962. /**
  48963. * Helper function to auto-create an ActionEvent from a source mesh.
  48964. * @param source The source mesh that triggered the event
  48965. * @param evt {Event} The original (browser) event
  48966. */
  48967. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48968. var scene = source.getScene();
  48969. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48970. };
  48971. /**
  48972. * Helper function to auto-create an ActionEvent from a source mesh.
  48973. * @param source The source sprite that triggered the event
  48974. * @param scene Scene associated with the sprite
  48975. * @param evt {Event} The original (browser) event
  48976. */
  48977. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48978. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48979. };
  48980. /**
  48981. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48982. * @param scene the scene where the event occurred
  48983. * @param evt {Event} The original (browser) event
  48984. */
  48985. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48986. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48987. };
  48988. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48989. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48990. };
  48991. return ActionEvent;
  48992. }());
  48993. BABYLON.ActionEvent = ActionEvent;
  48994. /**
  48995. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48996. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48997. */
  48998. var ActionManager = /** @class */ (function () {
  48999. function ActionManager(scene) {
  49000. // Members
  49001. this.actions = new Array();
  49002. this.hoverCursor = '';
  49003. this._scene = scene;
  49004. scene._actionManagers.push(this);
  49005. }
  49006. Object.defineProperty(ActionManager, "NothingTrigger", {
  49007. get: function () {
  49008. return ActionManager._NothingTrigger;
  49009. },
  49010. enumerable: true,
  49011. configurable: true
  49012. });
  49013. Object.defineProperty(ActionManager, "OnPickTrigger", {
  49014. get: function () {
  49015. return ActionManager._OnPickTrigger;
  49016. },
  49017. enumerable: true,
  49018. configurable: true
  49019. });
  49020. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  49021. get: function () {
  49022. return ActionManager._OnLeftPickTrigger;
  49023. },
  49024. enumerable: true,
  49025. configurable: true
  49026. });
  49027. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  49028. get: function () {
  49029. return ActionManager._OnRightPickTrigger;
  49030. },
  49031. enumerable: true,
  49032. configurable: true
  49033. });
  49034. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  49035. get: function () {
  49036. return ActionManager._OnCenterPickTrigger;
  49037. },
  49038. enumerable: true,
  49039. configurable: true
  49040. });
  49041. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  49042. get: function () {
  49043. return ActionManager._OnPickDownTrigger;
  49044. },
  49045. enumerable: true,
  49046. configurable: true
  49047. });
  49048. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  49049. get: function () {
  49050. return ActionManager._OnDoublePickTrigger;
  49051. },
  49052. enumerable: true,
  49053. configurable: true
  49054. });
  49055. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  49056. get: function () {
  49057. return ActionManager._OnPickUpTrigger;
  49058. },
  49059. enumerable: true,
  49060. configurable: true
  49061. });
  49062. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  49063. /// This trigger will only be raised if you also declared a OnPickDown
  49064. get: function () {
  49065. return ActionManager._OnPickOutTrigger;
  49066. },
  49067. enumerable: true,
  49068. configurable: true
  49069. });
  49070. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  49071. get: function () {
  49072. return ActionManager._OnLongPressTrigger;
  49073. },
  49074. enumerable: true,
  49075. configurable: true
  49076. });
  49077. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  49078. get: function () {
  49079. return ActionManager._OnPointerOverTrigger;
  49080. },
  49081. enumerable: true,
  49082. configurable: true
  49083. });
  49084. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  49085. get: function () {
  49086. return ActionManager._OnPointerOutTrigger;
  49087. },
  49088. enumerable: true,
  49089. configurable: true
  49090. });
  49091. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  49092. get: function () {
  49093. return ActionManager._OnEveryFrameTrigger;
  49094. },
  49095. enumerable: true,
  49096. configurable: true
  49097. });
  49098. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  49099. get: function () {
  49100. return ActionManager._OnIntersectionEnterTrigger;
  49101. },
  49102. enumerable: true,
  49103. configurable: true
  49104. });
  49105. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  49106. get: function () {
  49107. return ActionManager._OnIntersectionExitTrigger;
  49108. },
  49109. enumerable: true,
  49110. configurable: true
  49111. });
  49112. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  49113. get: function () {
  49114. return ActionManager._OnKeyDownTrigger;
  49115. },
  49116. enumerable: true,
  49117. configurable: true
  49118. });
  49119. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  49120. get: function () {
  49121. return ActionManager._OnKeyUpTrigger;
  49122. },
  49123. enumerable: true,
  49124. configurable: true
  49125. });
  49126. // Methods
  49127. ActionManager.prototype.dispose = function () {
  49128. var index = this._scene._actionManagers.indexOf(this);
  49129. for (var i = 0; i < this.actions.length; i++) {
  49130. var action = this.actions[i];
  49131. ActionManager.Triggers[action.trigger]--;
  49132. if (ActionManager.Triggers[action.trigger] === 0) {
  49133. delete ActionManager.Triggers[action.trigger];
  49134. }
  49135. }
  49136. if (index > -1) {
  49137. this._scene._actionManagers.splice(index, 1);
  49138. }
  49139. };
  49140. ActionManager.prototype.getScene = function () {
  49141. return this._scene;
  49142. };
  49143. /**
  49144. * Does this action manager handles actions of any of the given triggers
  49145. * @param {number[]} triggers - the triggers to be tested
  49146. * @return {boolean} whether one (or more) of the triggers is handeled
  49147. */
  49148. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  49149. for (var index = 0; index < this.actions.length; index++) {
  49150. var action = this.actions[index];
  49151. if (triggers.indexOf(action.trigger) > -1) {
  49152. return true;
  49153. }
  49154. }
  49155. return false;
  49156. };
  49157. /**
  49158. * Does this action manager handles actions of a given trigger
  49159. * @param {number} trigger - the trigger to be tested
  49160. * @return {boolean} whether the trigger is handeled
  49161. */
  49162. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  49163. for (var index = 0; index < this.actions.length; index++) {
  49164. var action = this.actions[index];
  49165. if (action.trigger === trigger) {
  49166. return true;
  49167. }
  49168. }
  49169. return false;
  49170. };
  49171. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  49172. /**
  49173. * Does this action manager has pointer triggers
  49174. * @return {boolean} whether or not it has pointer triggers
  49175. */
  49176. get: function () {
  49177. for (var index = 0; index < this.actions.length; index++) {
  49178. var action = this.actions[index];
  49179. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  49180. return true;
  49181. }
  49182. }
  49183. return false;
  49184. },
  49185. enumerable: true,
  49186. configurable: true
  49187. });
  49188. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  49189. /**
  49190. * Does this action manager has pick triggers
  49191. * @return {boolean} whether or not it has pick triggers
  49192. */
  49193. get: function () {
  49194. for (var index = 0; index < this.actions.length; index++) {
  49195. var action = this.actions[index];
  49196. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  49197. return true;
  49198. }
  49199. }
  49200. return false;
  49201. },
  49202. enumerable: true,
  49203. configurable: true
  49204. });
  49205. Object.defineProperty(ActionManager, "HasTriggers", {
  49206. /**
  49207. * Does exist one action manager with at least one trigger
  49208. * @return {boolean} whether or not it exists one action manager with one trigger
  49209. **/
  49210. get: function () {
  49211. for (var t in ActionManager.Triggers) {
  49212. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49213. return true;
  49214. }
  49215. }
  49216. return false;
  49217. },
  49218. enumerable: true,
  49219. configurable: true
  49220. });
  49221. Object.defineProperty(ActionManager, "HasPickTriggers", {
  49222. /**
  49223. * Does exist one action manager with at least one pick trigger
  49224. * @return {boolean} whether or not it exists one action manager with one pick trigger
  49225. **/
  49226. get: function () {
  49227. for (var t in ActionManager.Triggers) {
  49228. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49229. var t_int = parseInt(t);
  49230. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  49231. return true;
  49232. }
  49233. }
  49234. }
  49235. return false;
  49236. },
  49237. enumerable: true,
  49238. configurable: true
  49239. });
  49240. /**
  49241. * Does exist one action manager that handles actions of a given trigger
  49242. * @param {number} trigger - the trigger to be tested
  49243. * @return {boolean} whether the trigger is handeled by at least one action manager
  49244. **/
  49245. ActionManager.HasSpecificTrigger = function (trigger) {
  49246. for (var t in ActionManager.Triggers) {
  49247. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49248. var t_int = parseInt(t);
  49249. if (t_int === trigger) {
  49250. return true;
  49251. }
  49252. }
  49253. }
  49254. return false;
  49255. };
  49256. /**
  49257. * Registers an action to this action manager
  49258. * @param {BABYLON.Action} action - the action to be registered
  49259. * @return {BABYLON.Action} the action amended (prepared) after registration
  49260. */
  49261. ActionManager.prototype.registerAction = function (action) {
  49262. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  49263. if (this.getScene().actionManager !== this) {
  49264. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  49265. return null;
  49266. }
  49267. }
  49268. this.actions.push(action);
  49269. if (ActionManager.Triggers[action.trigger]) {
  49270. ActionManager.Triggers[action.trigger]++;
  49271. }
  49272. else {
  49273. ActionManager.Triggers[action.trigger] = 1;
  49274. }
  49275. action._actionManager = this;
  49276. action._prepare();
  49277. return action;
  49278. };
  49279. /**
  49280. * Unregisters an action to this action manager
  49281. * @param action The action to be unregistered
  49282. * @return whether the action has been unregistered
  49283. */
  49284. ActionManager.prototype.unregisterAction = function (action) {
  49285. var index = this.actions.indexOf(action);
  49286. if (index !== -1) {
  49287. this.actions.splice(index, 1);
  49288. ActionManager.Triggers[action.trigger] -= 1;
  49289. if (ActionManager.Triggers[action.trigger] === 0) {
  49290. delete ActionManager.Triggers[action.trigger];
  49291. }
  49292. delete action._actionManager;
  49293. return true;
  49294. }
  49295. return false;
  49296. };
  49297. /**
  49298. * Process a specific trigger
  49299. * @param {number} trigger - the trigger to process
  49300. * @param evt {BABYLON.ActionEvent} the event details to be processed
  49301. */
  49302. ActionManager.prototype.processTrigger = function (trigger, evt) {
  49303. for (var index = 0; index < this.actions.length; index++) {
  49304. var action = this.actions[index];
  49305. if (action.trigger === trigger) {
  49306. if (evt) {
  49307. if (trigger === ActionManager.OnKeyUpTrigger
  49308. || trigger === ActionManager.OnKeyDownTrigger) {
  49309. var parameter = action.getTriggerParameter();
  49310. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  49311. if (!parameter.toLowerCase) {
  49312. continue;
  49313. }
  49314. var lowerCase = parameter.toLowerCase();
  49315. if (lowerCase !== evt.sourceEvent.key) {
  49316. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  49317. var actualkey = String.fromCharCode(unicode).toLowerCase();
  49318. if (actualkey !== lowerCase) {
  49319. continue;
  49320. }
  49321. }
  49322. }
  49323. }
  49324. }
  49325. action._executeCurrent(evt);
  49326. }
  49327. }
  49328. };
  49329. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  49330. var properties = propertyPath.split(".");
  49331. for (var index = 0; index < properties.length - 1; index++) {
  49332. target = target[properties[index]];
  49333. }
  49334. return target;
  49335. };
  49336. ActionManager.prototype._getProperty = function (propertyPath) {
  49337. var properties = propertyPath.split(".");
  49338. return properties[properties.length - 1];
  49339. };
  49340. ActionManager.prototype.serialize = function (name) {
  49341. var root = {
  49342. children: new Array(),
  49343. name: name,
  49344. type: 3,
  49345. properties: new Array() // Empty for root but required
  49346. };
  49347. for (var i = 0; i < this.actions.length; i++) {
  49348. var triggerObject = {
  49349. type: 0,
  49350. children: new Array(),
  49351. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  49352. properties: new Array()
  49353. };
  49354. var triggerOptions = this.actions[i].triggerOptions;
  49355. if (triggerOptions && typeof triggerOptions !== "number") {
  49356. if (triggerOptions.parameter instanceof BABYLON.Node) {
  49357. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  49358. }
  49359. else {
  49360. var parameter = {};
  49361. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  49362. if (triggerOptions.parameter.mesh) {
  49363. parameter._meshId = triggerOptions.parameter.mesh.id;
  49364. }
  49365. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  49366. }
  49367. }
  49368. // Serialize child action, recursively
  49369. this.actions[i].serialize(triggerObject);
  49370. // Add serialized trigger
  49371. root.children.push(triggerObject);
  49372. }
  49373. return root;
  49374. };
  49375. ActionManager.Parse = function (parsedActions, object, scene) {
  49376. var actionManager = new ActionManager(scene);
  49377. if (object === null)
  49378. scene.actionManager = actionManager;
  49379. else
  49380. object.actionManager = actionManager;
  49381. // instanciate a new object
  49382. var instanciate = function (name, params) {
  49383. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  49384. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  49385. newInstance.constructor.apply(newInstance, params);
  49386. return newInstance;
  49387. };
  49388. var parseParameter = function (name, value, target, propertyPath) {
  49389. if (propertyPath === null) {
  49390. // String, boolean or float
  49391. var floatValue = parseFloat(value);
  49392. if (value === "true" || value === "false")
  49393. return value === "true";
  49394. else
  49395. return isNaN(floatValue) ? value : floatValue;
  49396. }
  49397. var effectiveTarget = propertyPath.split(".");
  49398. var values = value.split(",");
  49399. // Get effective Target
  49400. for (var i = 0; i < effectiveTarget.length; i++) {
  49401. target = target[effectiveTarget[i]];
  49402. }
  49403. // Return appropriate value with its type
  49404. if (typeof (target) === "boolean")
  49405. return values[0] === "true";
  49406. if (typeof (target) === "string")
  49407. return values[0];
  49408. // Parameters with multiple values such as Vector3 etc.
  49409. var split = new Array();
  49410. for (var i = 0; i < values.length; i++)
  49411. split.push(parseFloat(values[i]));
  49412. if (target instanceof BABYLON.Vector3)
  49413. return BABYLON.Vector3.FromArray(split);
  49414. if (target instanceof BABYLON.Vector4)
  49415. return BABYLON.Vector4.FromArray(split);
  49416. if (target instanceof BABYLON.Color3)
  49417. return BABYLON.Color3.FromArray(split);
  49418. if (target instanceof BABYLON.Color4)
  49419. return BABYLON.Color4.FromArray(split);
  49420. return parseFloat(values[0]);
  49421. };
  49422. // traverse graph per trigger
  49423. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  49424. if (combineArray === void 0) { combineArray = null; }
  49425. if (parsedAction.detached)
  49426. return;
  49427. var parameters = new Array();
  49428. var target = null;
  49429. var propertyPath = null;
  49430. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  49431. // Parameters
  49432. if (parsedAction.type === 2)
  49433. parameters.push(actionManager);
  49434. else
  49435. parameters.push(trigger);
  49436. if (combine) {
  49437. var actions = new Array();
  49438. for (var j = 0; j < parsedAction.combine.length; j++) {
  49439. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  49440. }
  49441. parameters.push(actions);
  49442. }
  49443. else {
  49444. for (var i = 0; i < parsedAction.properties.length; i++) {
  49445. var value = parsedAction.properties[i].value;
  49446. var name = parsedAction.properties[i].name;
  49447. var targetType = parsedAction.properties[i].targetType;
  49448. if (name === "target")
  49449. if (targetType !== null && targetType === "SceneProperties")
  49450. value = target = scene;
  49451. else
  49452. value = target = scene.getNodeByName(value);
  49453. else if (name === "parent")
  49454. value = scene.getNodeByName(value);
  49455. else if (name === "sound")
  49456. value = scene.getSoundByName(value);
  49457. else if (name !== "propertyPath") {
  49458. if (parsedAction.type === 2 && name === "operator")
  49459. value = BABYLON.ValueCondition[value];
  49460. else
  49461. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  49462. }
  49463. else {
  49464. propertyPath = value;
  49465. }
  49466. parameters.push(value);
  49467. }
  49468. }
  49469. if (combineArray === null) {
  49470. parameters.push(condition);
  49471. }
  49472. else {
  49473. parameters.push(null);
  49474. }
  49475. // If interpolate value action
  49476. if (parsedAction.name === "InterpolateValueAction") {
  49477. var param = parameters[parameters.length - 2];
  49478. parameters[parameters.length - 1] = param;
  49479. parameters[parameters.length - 2] = condition;
  49480. }
  49481. // Action or condition(s) and not CombineAction
  49482. var newAction = instanciate(parsedAction.name, parameters);
  49483. if (newAction instanceof BABYLON.Condition && condition !== null) {
  49484. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  49485. if (action)
  49486. action.then(nothing);
  49487. else
  49488. actionManager.registerAction(nothing);
  49489. action = nothing;
  49490. }
  49491. if (combineArray === null) {
  49492. if (newAction instanceof BABYLON.Condition) {
  49493. condition = newAction;
  49494. newAction = action;
  49495. }
  49496. else {
  49497. condition = null;
  49498. if (action)
  49499. action.then(newAction);
  49500. else
  49501. actionManager.registerAction(newAction);
  49502. }
  49503. }
  49504. else {
  49505. combineArray.push(newAction);
  49506. }
  49507. for (var i = 0; i < parsedAction.children.length; i++)
  49508. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  49509. };
  49510. // triggers
  49511. for (var i = 0; i < parsedActions.children.length; i++) {
  49512. var triggerParams;
  49513. var trigger = parsedActions.children[i];
  49514. if (trigger.properties.length > 0) {
  49515. var param = trigger.properties[0].value;
  49516. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  49517. if (value._meshId) {
  49518. value.mesh = scene.getMeshByID(value._meshId);
  49519. }
  49520. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  49521. }
  49522. else
  49523. triggerParams = ActionManager[trigger.name];
  49524. for (var j = 0; j < trigger.children.length; j++) {
  49525. if (!trigger.detached)
  49526. traverse(trigger.children[j], triggerParams, null, null);
  49527. }
  49528. }
  49529. };
  49530. ActionManager.GetTriggerName = function (trigger) {
  49531. switch (trigger) {
  49532. case 0: return "NothingTrigger";
  49533. case 1: return "OnPickTrigger";
  49534. case 2: return "OnLeftPickTrigger";
  49535. case 3: return "OnRightPickTrigger";
  49536. case 4: return "OnCenterPickTrigger";
  49537. case 5: return "OnPickDownTrigger";
  49538. case 6: return "OnPickUpTrigger";
  49539. case 7: return "OnLongPressTrigger";
  49540. case 8: return "OnPointerOverTrigger";
  49541. case 9: return "OnPointerOutTrigger";
  49542. case 10: return "OnEveryFrameTrigger";
  49543. case 11: return "OnIntersectionEnterTrigger";
  49544. case 12: return "OnIntersectionExitTrigger";
  49545. case 13: return "OnKeyDownTrigger";
  49546. case 14: return "OnKeyUpTrigger";
  49547. case 15: return "OnPickOutTrigger";
  49548. default: return "";
  49549. }
  49550. };
  49551. // Statics
  49552. ActionManager._NothingTrigger = 0;
  49553. ActionManager._OnPickTrigger = 1;
  49554. ActionManager._OnLeftPickTrigger = 2;
  49555. ActionManager._OnRightPickTrigger = 3;
  49556. ActionManager._OnCenterPickTrigger = 4;
  49557. ActionManager._OnPickDownTrigger = 5;
  49558. ActionManager._OnDoublePickTrigger = 6;
  49559. ActionManager._OnPickUpTrigger = 7;
  49560. ActionManager._OnLongPressTrigger = 8;
  49561. ActionManager._OnPointerOverTrigger = 9;
  49562. ActionManager._OnPointerOutTrigger = 10;
  49563. ActionManager._OnEveryFrameTrigger = 11;
  49564. ActionManager._OnIntersectionEnterTrigger = 12;
  49565. ActionManager._OnIntersectionExitTrigger = 13;
  49566. ActionManager._OnKeyDownTrigger = 14;
  49567. ActionManager._OnKeyUpTrigger = 15;
  49568. ActionManager._OnPickOutTrigger = 16;
  49569. ActionManager.Triggers = {};
  49570. return ActionManager;
  49571. }());
  49572. BABYLON.ActionManager = ActionManager;
  49573. })(BABYLON || (BABYLON = {}));
  49574. //# sourceMappingURL=babylon.actionManager.js.map
  49575. "use strict";
  49576. var BABYLON;
  49577. (function (BABYLON) {
  49578. var InterpolateValueAction = /** @class */ (function (_super) {
  49579. __extends(InterpolateValueAction, _super);
  49580. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  49581. if (duration === void 0) { duration = 1000; }
  49582. var _this = _super.call(this, triggerOptions, condition) || this;
  49583. _this.propertyPath = propertyPath;
  49584. _this.value = value;
  49585. _this.duration = duration;
  49586. _this.stopOtherAnimations = stopOtherAnimations;
  49587. _this.onInterpolationDone = onInterpolationDone;
  49588. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49589. _this._target = _this._effectiveTarget = target;
  49590. return _this;
  49591. }
  49592. InterpolateValueAction.prototype._prepare = function () {
  49593. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49594. this._property = this._getProperty(this.propertyPath);
  49595. };
  49596. InterpolateValueAction.prototype.execute = function () {
  49597. var _this = this;
  49598. var scene = this._actionManager.getScene();
  49599. var keys = [
  49600. {
  49601. frame: 0,
  49602. value: this._effectiveTarget[this._property]
  49603. }, {
  49604. frame: 100,
  49605. value: this.value
  49606. }
  49607. ];
  49608. var dataType;
  49609. if (typeof this.value === "number") {
  49610. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49611. }
  49612. else if (this.value instanceof BABYLON.Color3) {
  49613. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49614. }
  49615. else if (this.value instanceof BABYLON.Vector3) {
  49616. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49617. }
  49618. else if (this.value instanceof BABYLON.Matrix) {
  49619. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49620. }
  49621. else if (this.value instanceof BABYLON.Quaternion) {
  49622. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49623. }
  49624. else {
  49625. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49626. return;
  49627. }
  49628. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49629. animation.setKeys(keys);
  49630. if (this.stopOtherAnimations) {
  49631. scene.stopAnimation(this._effectiveTarget);
  49632. }
  49633. var wrapper = function () {
  49634. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49635. if (_this.onInterpolationDone) {
  49636. _this.onInterpolationDone();
  49637. }
  49638. };
  49639. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49640. };
  49641. InterpolateValueAction.prototype.serialize = function (parent) {
  49642. return _super.prototype._serialize.call(this, {
  49643. name: "InterpolateValueAction",
  49644. properties: [
  49645. BABYLON.Action._GetTargetProperty(this._target),
  49646. { name: "propertyPath", value: this.propertyPath },
  49647. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49648. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49649. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49650. ]
  49651. }, parent);
  49652. };
  49653. return InterpolateValueAction;
  49654. }(BABYLON.Action));
  49655. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49656. })(BABYLON || (BABYLON = {}));
  49657. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49658. "use strict";
  49659. var BABYLON;
  49660. (function (BABYLON) {
  49661. var SwitchBooleanAction = /** @class */ (function (_super) {
  49662. __extends(SwitchBooleanAction, _super);
  49663. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49664. var _this = _super.call(this, triggerOptions, condition) || this;
  49665. _this.propertyPath = propertyPath;
  49666. _this._target = _this._effectiveTarget = target;
  49667. return _this;
  49668. }
  49669. SwitchBooleanAction.prototype._prepare = function () {
  49670. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49671. this._property = this._getProperty(this.propertyPath);
  49672. };
  49673. SwitchBooleanAction.prototype.execute = function () {
  49674. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49675. };
  49676. SwitchBooleanAction.prototype.serialize = function (parent) {
  49677. return _super.prototype._serialize.call(this, {
  49678. name: "SwitchBooleanAction",
  49679. properties: [
  49680. BABYLON.Action._GetTargetProperty(this._target),
  49681. { name: "propertyPath", value: this.propertyPath }
  49682. ]
  49683. }, parent);
  49684. };
  49685. return SwitchBooleanAction;
  49686. }(BABYLON.Action));
  49687. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49688. var SetStateAction = /** @class */ (function (_super) {
  49689. __extends(SetStateAction, _super);
  49690. function SetStateAction(triggerOptions, target, value, condition) {
  49691. var _this = _super.call(this, triggerOptions, condition) || this;
  49692. _this.value = value;
  49693. _this._target = target;
  49694. return _this;
  49695. }
  49696. SetStateAction.prototype.execute = function () {
  49697. this._target.state = this.value;
  49698. };
  49699. SetStateAction.prototype.serialize = function (parent) {
  49700. return _super.prototype._serialize.call(this, {
  49701. name: "SetStateAction",
  49702. properties: [
  49703. BABYLON.Action._GetTargetProperty(this._target),
  49704. { name: "value", value: this.value }
  49705. ]
  49706. }, parent);
  49707. };
  49708. return SetStateAction;
  49709. }(BABYLON.Action));
  49710. BABYLON.SetStateAction = SetStateAction;
  49711. var SetValueAction = /** @class */ (function (_super) {
  49712. __extends(SetValueAction, _super);
  49713. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49714. var _this = _super.call(this, triggerOptions, condition) || this;
  49715. _this.propertyPath = propertyPath;
  49716. _this.value = value;
  49717. _this._target = _this._effectiveTarget = target;
  49718. return _this;
  49719. }
  49720. SetValueAction.prototype._prepare = function () {
  49721. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49722. this._property = this._getProperty(this.propertyPath);
  49723. };
  49724. SetValueAction.prototype.execute = function () {
  49725. this._effectiveTarget[this._property] = this.value;
  49726. if (this._target.markAsDirty) {
  49727. this._target.markAsDirty(this._property);
  49728. }
  49729. };
  49730. SetValueAction.prototype.serialize = function (parent) {
  49731. return _super.prototype._serialize.call(this, {
  49732. name: "SetValueAction",
  49733. properties: [
  49734. BABYLON.Action._GetTargetProperty(this._target),
  49735. { name: "propertyPath", value: this.propertyPath },
  49736. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49737. ]
  49738. }, parent);
  49739. };
  49740. return SetValueAction;
  49741. }(BABYLON.Action));
  49742. BABYLON.SetValueAction = SetValueAction;
  49743. var IncrementValueAction = /** @class */ (function (_super) {
  49744. __extends(IncrementValueAction, _super);
  49745. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49746. var _this = _super.call(this, triggerOptions, condition) || this;
  49747. _this.propertyPath = propertyPath;
  49748. _this.value = value;
  49749. _this._target = _this._effectiveTarget = target;
  49750. return _this;
  49751. }
  49752. IncrementValueAction.prototype._prepare = function () {
  49753. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49754. this._property = this._getProperty(this.propertyPath);
  49755. if (typeof this._effectiveTarget[this._property] !== "number") {
  49756. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49757. }
  49758. };
  49759. IncrementValueAction.prototype.execute = function () {
  49760. this._effectiveTarget[this._property] += this.value;
  49761. if (this._target.markAsDirty) {
  49762. this._target.markAsDirty(this._property);
  49763. }
  49764. };
  49765. IncrementValueAction.prototype.serialize = function (parent) {
  49766. return _super.prototype._serialize.call(this, {
  49767. name: "IncrementValueAction",
  49768. properties: [
  49769. BABYLON.Action._GetTargetProperty(this._target),
  49770. { name: "propertyPath", value: this.propertyPath },
  49771. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49772. ]
  49773. }, parent);
  49774. };
  49775. return IncrementValueAction;
  49776. }(BABYLON.Action));
  49777. BABYLON.IncrementValueAction = IncrementValueAction;
  49778. var PlayAnimationAction = /** @class */ (function (_super) {
  49779. __extends(PlayAnimationAction, _super);
  49780. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49781. var _this = _super.call(this, triggerOptions, condition) || this;
  49782. _this.from = from;
  49783. _this.to = to;
  49784. _this.loop = loop;
  49785. _this._target = target;
  49786. return _this;
  49787. }
  49788. PlayAnimationAction.prototype._prepare = function () {
  49789. };
  49790. PlayAnimationAction.prototype.execute = function () {
  49791. var scene = this._actionManager.getScene();
  49792. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49793. };
  49794. PlayAnimationAction.prototype.serialize = function (parent) {
  49795. return _super.prototype._serialize.call(this, {
  49796. name: "PlayAnimationAction",
  49797. properties: [
  49798. BABYLON.Action._GetTargetProperty(this._target),
  49799. { name: "from", value: String(this.from) },
  49800. { name: "to", value: String(this.to) },
  49801. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49802. ]
  49803. }, parent);
  49804. };
  49805. return PlayAnimationAction;
  49806. }(BABYLON.Action));
  49807. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49808. var StopAnimationAction = /** @class */ (function (_super) {
  49809. __extends(StopAnimationAction, _super);
  49810. function StopAnimationAction(triggerOptions, target, condition) {
  49811. var _this = _super.call(this, triggerOptions, condition) || this;
  49812. _this._target = target;
  49813. return _this;
  49814. }
  49815. StopAnimationAction.prototype._prepare = function () {
  49816. };
  49817. StopAnimationAction.prototype.execute = function () {
  49818. var scene = this._actionManager.getScene();
  49819. scene.stopAnimation(this._target);
  49820. };
  49821. StopAnimationAction.prototype.serialize = function (parent) {
  49822. return _super.prototype._serialize.call(this, {
  49823. name: "StopAnimationAction",
  49824. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49825. }, parent);
  49826. };
  49827. return StopAnimationAction;
  49828. }(BABYLON.Action));
  49829. BABYLON.StopAnimationAction = StopAnimationAction;
  49830. var DoNothingAction = /** @class */ (function (_super) {
  49831. __extends(DoNothingAction, _super);
  49832. function DoNothingAction(triggerOptions, condition) {
  49833. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49834. return _super.call(this, triggerOptions, condition) || this;
  49835. }
  49836. DoNothingAction.prototype.execute = function () {
  49837. };
  49838. DoNothingAction.prototype.serialize = function (parent) {
  49839. return _super.prototype._serialize.call(this, {
  49840. name: "DoNothingAction",
  49841. properties: []
  49842. }, parent);
  49843. };
  49844. return DoNothingAction;
  49845. }(BABYLON.Action));
  49846. BABYLON.DoNothingAction = DoNothingAction;
  49847. var CombineAction = /** @class */ (function (_super) {
  49848. __extends(CombineAction, _super);
  49849. function CombineAction(triggerOptions, children, condition) {
  49850. var _this = _super.call(this, triggerOptions, condition) || this;
  49851. _this.children = children;
  49852. return _this;
  49853. }
  49854. CombineAction.prototype._prepare = function () {
  49855. for (var index = 0; index < this.children.length; index++) {
  49856. this.children[index]._actionManager = this._actionManager;
  49857. this.children[index]._prepare();
  49858. }
  49859. };
  49860. CombineAction.prototype.execute = function (evt) {
  49861. for (var index = 0; index < this.children.length; index++) {
  49862. this.children[index].execute(evt);
  49863. }
  49864. };
  49865. CombineAction.prototype.serialize = function (parent) {
  49866. var serializationObject = _super.prototype._serialize.call(this, {
  49867. name: "CombineAction",
  49868. properties: [],
  49869. combine: []
  49870. }, parent);
  49871. for (var i = 0; i < this.children.length; i++) {
  49872. serializationObject.combine.push(this.children[i].serialize(null));
  49873. }
  49874. return serializationObject;
  49875. };
  49876. return CombineAction;
  49877. }(BABYLON.Action));
  49878. BABYLON.CombineAction = CombineAction;
  49879. var ExecuteCodeAction = /** @class */ (function (_super) {
  49880. __extends(ExecuteCodeAction, _super);
  49881. function ExecuteCodeAction(triggerOptions, func, condition) {
  49882. var _this = _super.call(this, triggerOptions, condition) || this;
  49883. _this.func = func;
  49884. return _this;
  49885. }
  49886. ExecuteCodeAction.prototype.execute = function (evt) {
  49887. this.func(evt);
  49888. };
  49889. return ExecuteCodeAction;
  49890. }(BABYLON.Action));
  49891. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49892. var SetParentAction = /** @class */ (function (_super) {
  49893. __extends(SetParentAction, _super);
  49894. function SetParentAction(triggerOptions, target, parent, condition) {
  49895. var _this = _super.call(this, triggerOptions, condition) || this;
  49896. _this._target = target;
  49897. _this._parent = parent;
  49898. return _this;
  49899. }
  49900. SetParentAction.prototype._prepare = function () {
  49901. };
  49902. SetParentAction.prototype.execute = function () {
  49903. if (this._target.parent === this._parent) {
  49904. return;
  49905. }
  49906. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49907. invertParentWorldMatrix.invert();
  49908. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49909. this._target.parent = this._parent;
  49910. };
  49911. SetParentAction.prototype.serialize = function (parent) {
  49912. return _super.prototype._serialize.call(this, {
  49913. name: "SetParentAction",
  49914. properties: [
  49915. BABYLON.Action._GetTargetProperty(this._target),
  49916. BABYLON.Action._GetTargetProperty(this._parent),
  49917. ]
  49918. }, parent);
  49919. };
  49920. return SetParentAction;
  49921. }(BABYLON.Action));
  49922. BABYLON.SetParentAction = SetParentAction;
  49923. var PlaySoundAction = /** @class */ (function (_super) {
  49924. __extends(PlaySoundAction, _super);
  49925. function PlaySoundAction(triggerOptions, sound, condition) {
  49926. var _this = _super.call(this, triggerOptions, condition) || this;
  49927. _this._sound = sound;
  49928. return _this;
  49929. }
  49930. PlaySoundAction.prototype._prepare = function () {
  49931. };
  49932. PlaySoundAction.prototype.execute = function () {
  49933. if (this._sound !== undefined)
  49934. this._sound.play();
  49935. };
  49936. PlaySoundAction.prototype.serialize = function (parent) {
  49937. return _super.prototype._serialize.call(this, {
  49938. name: "PlaySoundAction",
  49939. properties: [{ name: "sound", value: this._sound.name }]
  49940. }, parent);
  49941. };
  49942. return PlaySoundAction;
  49943. }(BABYLON.Action));
  49944. BABYLON.PlaySoundAction = PlaySoundAction;
  49945. var StopSoundAction = /** @class */ (function (_super) {
  49946. __extends(StopSoundAction, _super);
  49947. function StopSoundAction(triggerOptions, sound, condition) {
  49948. var _this = _super.call(this, triggerOptions, condition) || this;
  49949. _this._sound = sound;
  49950. return _this;
  49951. }
  49952. StopSoundAction.prototype._prepare = function () {
  49953. };
  49954. StopSoundAction.prototype.execute = function () {
  49955. if (this._sound !== undefined)
  49956. this._sound.stop();
  49957. };
  49958. StopSoundAction.prototype.serialize = function (parent) {
  49959. return _super.prototype._serialize.call(this, {
  49960. name: "StopSoundAction",
  49961. properties: [{ name: "sound", value: this._sound.name }]
  49962. }, parent);
  49963. };
  49964. return StopSoundAction;
  49965. }(BABYLON.Action));
  49966. BABYLON.StopSoundAction = StopSoundAction;
  49967. })(BABYLON || (BABYLON = {}));
  49968. //# sourceMappingURL=babylon.directActions.js.map
  49969. "use strict";
  49970. var BABYLON;
  49971. (function (BABYLON) {
  49972. var SpriteManager = /** @class */ (function () {
  49973. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49974. if (epsilon === void 0) { epsilon = 0.01; }
  49975. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49976. this.name = name;
  49977. this.sprites = new Array();
  49978. this.renderingGroupId = 0;
  49979. this.layerMask = 0x0FFFFFFF;
  49980. this.fogEnabled = true;
  49981. this.isPickable = false;
  49982. /**
  49983. * An event triggered when the manager is disposed.
  49984. * @type {BABYLON.Observable}
  49985. */
  49986. this.onDisposeObservable = new BABYLON.Observable();
  49987. this._vertexBuffers = {};
  49988. this._capacity = capacity;
  49989. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49990. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49991. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49992. if (cellSize.width && cellSize.height) {
  49993. this.cellWidth = cellSize.width;
  49994. this.cellHeight = cellSize.height;
  49995. }
  49996. else if (cellSize !== undefined) {
  49997. this.cellWidth = cellSize;
  49998. this.cellHeight = cellSize;
  49999. }
  50000. else {
  50001. return;
  50002. }
  50003. this._epsilon = epsilon;
  50004. this._scene = scene;
  50005. this._scene.spriteManagers.push(this);
  50006. var indices = [];
  50007. var index = 0;
  50008. for (var count = 0; count < capacity; count++) {
  50009. indices.push(index);
  50010. indices.push(index + 1);
  50011. indices.push(index + 2);
  50012. indices.push(index);
  50013. indices.push(index + 2);
  50014. indices.push(index + 3);
  50015. index += 4;
  50016. }
  50017. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  50018. // VBO
  50019. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  50020. this._vertexData = new Float32Array(capacity * 16 * 4);
  50021. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  50022. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  50023. var options = this._buffer.createVertexBuffer("options", 4, 4);
  50024. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  50025. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  50026. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50027. this._vertexBuffers["options"] = options;
  50028. this._vertexBuffers["cellInfo"] = cellInfo;
  50029. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50030. // Effects
  50031. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  50032. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  50033. }
  50034. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  50035. set: function (callback) {
  50036. if (this._onDisposeObserver) {
  50037. this.onDisposeObservable.remove(this._onDisposeObserver);
  50038. }
  50039. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50040. },
  50041. enumerable: true,
  50042. configurable: true
  50043. });
  50044. Object.defineProperty(SpriteManager.prototype, "texture", {
  50045. get: function () {
  50046. return this._spriteTexture;
  50047. },
  50048. set: function (value) {
  50049. this._spriteTexture = value;
  50050. },
  50051. enumerable: true,
  50052. configurable: true
  50053. });
  50054. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  50055. var arrayOffset = index * 16;
  50056. if (offsetX === 0)
  50057. offsetX = this._epsilon;
  50058. else if (offsetX === 1)
  50059. offsetX = 1 - this._epsilon;
  50060. if (offsetY === 0)
  50061. offsetY = this._epsilon;
  50062. else if (offsetY === 1)
  50063. offsetY = 1 - this._epsilon;
  50064. this._vertexData[arrayOffset] = sprite.position.x;
  50065. this._vertexData[arrayOffset + 1] = sprite.position.y;
  50066. this._vertexData[arrayOffset + 2] = sprite.position.z;
  50067. this._vertexData[arrayOffset + 3] = sprite.angle;
  50068. this._vertexData[arrayOffset + 4] = sprite.width;
  50069. this._vertexData[arrayOffset + 5] = sprite.height;
  50070. this._vertexData[arrayOffset + 6] = offsetX;
  50071. this._vertexData[arrayOffset + 7] = offsetY;
  50072. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  50073. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  50074. var offset = (sprite.cellIndex / rowSize) >> 0;
  50075. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  50076. this._vertexData[arrayOffset + 11] = offset;
  50077. // Color
  50078. this._vertexData[arrayOffset + 12] = sprite.color.r;
  50079. this._vertexData[arrayOffset + 13] = sprite.color.g;
  50080. this._vertexData[arrayOffset + 14] = sprite.color.b;
  50081. this._vertexData[arrayOffset + 15] = sprite.color.a;
  50082. };
  50083. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  50084. var count = Math.min(this._capacity, this.sprites.length);
  50085. var min = BABYLON.Vector3.Zero();
  50086. var max = BABYLON.Vector3.Zero();
  50087. var distance = Number.MAX_VALUE;
  50088. var currentSprite = null;
  50089. var cameraSpacePosition = BABYLON.Vector3.Zero();
  50090. var cameraView = camera.getViewMatrix();
  50091. for (var index = 0; index < count; index++) {
  50092. var sprite = this.sprites[index];
  50093. if (!sprite) {
  50094. continue;
  50095. }
  50096. if (predicate) {
  50097. if (!predicate(sprite)) {
  50098. continue;
  50099. }
  50100. }
  50101. else if (!sprite.isPickable) {
  50102. continue;
  50103. }
  50104. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  50105. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  50106. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  50107. if (ray.intersectsBoxMinMax(min, max)) {
  50108. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  50109. if (distance > currentDistance) {
  50110. distance = currentDistance;
  50111. currentSprite = sprite;
  50112. if (fastCheck) {
  50113. break;
  50114. }
  50115. }
  50116. }
  50117. }
  50118. if (currentSprite) {
  50119. var result = new BABYLON.PickingInfo();
  50120. result.hit = true;
  50121. result.pickedSprite = currentSprite;
  50122. result.distance = distance;
  50123. return result;
  50124. }
  50125. return null;
  50126. };
  50127. SpriteManager.prototype.render = function () {
  50128. // Check
  50129. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  50130. return;
  50131. var engine = this._scene.getEngine();
  50132. var baseSize = this._spriteTexture.getBaseSize();
  50133. // Sprites
  50134. var deltaTime = engine.getDeltaTime();
  50135. var max = Math.min(this._capacity, this.sprites.length);
  50136. var rowSize = baseSize.width / this.cellWidth;
  50137. var offset = 0;
  50138. for (var index = 0; index < max; index++) {
  50139. var sprite = this.sprites[index];
  50140. if (!sprite) {
  50141. continue;
  50142. }
  50143. sprite._animate(deltaTime);
  50144. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  50145. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  50146. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  50147. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  50148. }
  50149. this._buffer.update(this._vertexData);
  50150. // Render
  50151. var effect = this._effectBase;
  50152. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50153. effect = this._effectFog;
  50154. }
  50155. engine.enableEffect(effect);
  50156. var viewMatrix = this._scene.getViewMatrix();
  50157. effect.setTexture("diffuseSampler", this._spriteTexture);
  50158. effect.setMatrix("view", viewMatrix);
  50159. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50160. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  50161. // Fog
  50162. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50163. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  50164. effect.setColor3("vFogColor", this._scene.fogColor);
  50165. }
  50166. // VBOs
  50167. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50168. // Draw order
  50169. engine.setDepthFunctionToLessOrEqual();
  50170. effect.setBool("alphaTest", true);
  50171. engine.setColorWrite(false);
  50172. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50173. engine.setColorWrite(true);
  50174. effect.setBool("alphaTest", false);
  50175. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50176. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50177. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50178. };
  50179. SpriteManager.prototype.dispose = function () {
  50180. if (this._buffer) {
  50181. this._buffer.dispose();
  50182. this._buffer = null;
  50183. }
  50184. if (this._indexBuffer) {
  50185. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50186. this._indexBuffer = null;
  50187. }
  50188. if (this._spriteTexture) {
  50189. this._spriteTexture.dispose();
  50190. this._spriteTexture = null;
  50191. }
  50192. // Remove from scene
  50193. var index = this._scene.spriteManagers.indexOf(this);
  50194. this._scene.spriteManagers.splice(index, 1);
  50195. // Callback
  50196. this.onDisposeObservable.notifyObservers(this);
  50197. this.onDisposeObservable.clear();
  50198. };
  50199. return SpriteManager;
  50200. }());
  50201. BABYLON.SpriteManager = SpriteManager;
  50202. })(BABYLON || (BABYLON = {}));
  50203. //# sourceMappingURL=babylon.spriteManager.js.map
  50204. "use strict";
  50205. var BABYLON;
  50206. (function (BABYLON) {
  50207. var Sprite = /** @class */ (function () {
  50208. function Sprite(name, manager) {
  50209. this.name = name;
  50210. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50211. this.width = 1.0;
  50212. this.height = 1.0;
  50213. this.angle = 0;
  50214. this.cellIndex = 0;
  50215. this.invertU = 0;
  50216. this.invertV = 0;
  50217. this.animations = new Array();
  50218. this.isPickable = false;
  50219. this._animationStarted = false;
  50220. this._loopAnimation = false;
  50221. this._fromIndex = 0;
  50222. this._toIndex = 0;
  50223. this._delay = 0;
  50224. this._direction = 1;
  50225. this._time = 0;
  50226. this._manager = manager;
  50227. this._manager.sprites.push(this);
  50228. this.position = BABYLON.Vector3.Zero();
  50229. }
  50230. Object.defineProperty(Sprite.prototype, "size", {
  50231. get: function () {
  50232. return this.width;
  50233. },
  50234. set: function (value) {
  50235. this.width = value;
  50236. this.height = value;
  50237. },
  50238. enumerable: true,
  50239. configurable: true
  50240. });
  50241. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  50242. this._fromIndex = from;
  50243. this._toIndex = to;
  50244. this._loopAnimation = loop;
  50245. this._delay = delay;
  50246. this._animationStarted = true;
  50247. this._direction = from < to ? 1 : -1;
  50248. this.cellIndex = from;
  50249. this._time = 0;
  50250. this._onAnimationEnd = onAnimationEnd;
  50251. };
  50252. Sprite.prototype.stopAnimation = function () {
  50253. this._animationStarted = false;
  50254. };
  50255. Sprite.prototype._animate = function (deltaTime) {
  50256. if (!this._animationStarted)
  50257. return;
  50258. this._time += deltaTime;
  50259. if (this._time > this._delay) {
  50260. this._time = this._time % this._delay;
  50261. this.cellIndex += this._direction;
  50262. if (this.cellIndex > this._toIndex) {
  50263. if (this._loopAnimation) {
  50264. this.cellIndex = this._fromIndex;
  50265. }
  50266. else {
  50267. this.cellIndex = this._toIndex;
  50268. this._animationStarted = false;
  50269. if (this._onAnimationEnd) {
  50270. this._onAnimationEnd();
  50271. }
  50272. if (this.disposeWhenFinishedAnimating) {
  50273. this.dispose();
  50274. }
  50275. }
  50276. }
  50277. }
  50278. };
  50279. Sprite.prototype.dispose = function () {
  50280. for (var i = 0; i < this._manager.sprites.length; i++) {
  50281. if (this._manager.sprites[i] == this) {
  50282. this._manager.sprites.splice(i, 1);
  50283. }
  50284. }
  50285. };
  50286. return Sprite;
  50287. }());
  50288. BABYLON.Sprite = Sprite;
  50289. })(BABYLON || (BABYLON = {}));
  50290. //# sourceMappingURL=babylon.sprite.js.map
  50291. "use strict";
  50292. var BABYLON;
  50293. (function (BABYLON) {
  50294. var IntersectionInfo = /** @class */ (function () {
  50295. function IntersectionInfo(bu, bv, distance) {
  50296. this.bu = bu;
  50297. this.bv = bv;
  50298. this.distance = distance;
  50299. this.faceId = 0;
  50300. this.subMeshId = 0;
  50301. }
  50302. return IntersectionInfo;
  50303. }());
  50304. BABYLON.IntersectionInfo = IntersectionInfo;
  50305. var PickingInfo = /** @class */ (function () {
  50306. function PickingInfo() {
  50307. this.hit = false;
  50308. this.distance = 0;
  50309. this.pickedPoint = null;
  50310. this.pickedMesh = null;
  50311. this.bu = 0;
  50312. this.bv = 0;
  50313. this.faceId = -1;
  50314. this.subMeshId = 0;
  50315. this.pickedSprite = null;
  50316. }
  50317. // Methods
  50318. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  50319. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  50320. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  50321. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50322. return null;
  50323. }
  50324. var indices = this.pickedMesh.getIndices();
  50325. if (!indices) {
  50326. return null;
  50327. }
  50328. var result;
  50329. if (useVerticesNormals) {
  50330. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50331. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  50332. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  50333. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  50334. normal0 = normal0.scale(this.bu);
  50335. normal1 = normal1.scale(this.bv);
  50336. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  50337. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  50338. }
  50339. else {
  50340. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50341. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  50342. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  50343. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  50344. var p1p2 = vertex1.subtract(vertex2);
  50345. var p3p2 = vertex3.subtract(vertex2);
  50346. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  50347. }
  50348. if (useWorldCoordinates) {
  50349. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  50350. }
  50351. return BABYLON.Vector3.Normalize(result);
  50352. };
  50353. PickingInfo.prototype.getTextureCoordinates = function () {
  50354. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50355. return null;
  50356. }
  50357. var indices = this.pickedMesh.getIndices();
  50358. if (!indices) {
  50359. return null;
  50360. }
  50361. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50362. if (!uvs) {
  50363. return null;
  50364. }
  50365. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  50366. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  50367. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  50368. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  50369. uv1 = uv1.scale(this.bu);
  50370. uv2 = uv2.scale(this.bv);
  50371. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  50372. };
  50373. return PickingInfo;
  50374. }());
  50375. BABYLON.PickingInfo = PickingInfo;
  50376. })(BABYLON || (BABYLON = {}));
  50377. //# sourceMappingURL=babylon.pickingInfo.js.map
  50378. "use strict";
  50379. var BABYLON;
  50380. (function (BABYLON) {
  50381. var Ray = /** @class */ (function () {
  50382. function Ray(origin, direction, length) {
  50383. if (length === void 0) { length = Number.MAX_VALUE; }
  50384. this.origin = origin;
  50385. this.direction = direction;
  50386. this.length = length;
  50387. }
  50388. // Methods
  50389. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  50390. var d = 0.0;
  50391. var maxValue = Number.MAX_VALUE;
  50392. var inv;
  50393. var min;
  50394. var max;
  50395. var temp;
  50396. if (Math.abs(this.direction.x) < 0.0000001) {
  50397. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  50398. return false;
  50399. }
  50400. }
  50401. else {
  50402. inv = 1.0 / this.direction.x;
  50403. min = (minimum.x - this.origin.x) * inv;
  50404. max = (maximum.x - this.origin.x) * inv;
  50405. if (max === -Infinity) {
  50406. max = Infinity;
  50407. }
  50408. if (min > max) {
  50409. temp = min;
  50410. min = max;
  50411. max = temp;
  50412. }
  50413. d = Math.max(min, d);
  50414. maxValue = Math.min(max, maxValue);
  50415. if (d > maxValue) {
  50416. return false;
  50417. }
  50418. }
  50419. if (Math.abs(this.direction.y) < 0.0000001) {
  50420. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  50421. return false;
  50422. }
  50423. }
  50424. else {
  50425. inv = 1.0 / this.direction.y;
  50426. min = (minimum.y - this.origin.y) * inv;
  50427. max = (maximum.y - this.origin.y) * inv;
  50428. if (max === -Infinity) {
  50429. max = Infinity;
  50430. }
  50431. if (min > max) {
  50432. temp = min;
  50433. min = max;
  50434. max = temp;
  50435. }
  50436. d = Math.max(min, d);
  50437. maxValue = Math.min(max, maxValue);
  50438. if (d > maxValue) {
  50439. return false;
  50440. }
  50441. }
  50442. if (Math.abs(this.direction.z) < 0.0000001) {
  50443. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  50444. return false;
  50445. }
  50446. }
  50447. else {
  50448. inv = 1.0 / this.direction.z;
  50449. min = (minimum.z - this.origin.z) * inv;
  50450. max = (maximum.z - this.origin.z) * inv;
  50451. if (max === -Infinity) {
  50452. max = Infinity;
  50453. }
  50454. if (min > max) {
  50455. temp = min;
  50456. min = max;
  50457. max = temp;
  50458. }
  50459. d = Math.max(min, d);
  50460. maxValue = Math.min(max, maxValue);
  50461. if (d > maxValue) {
  50462. return false;
  50463. }
  50464. }
  50465. return true;
  50466. };
  50467. Ray.prototype.intersectsBox = function (box) {
  50468. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  50469. };
  50470. Ray.prototype.intersectsSphere = function (sphere) {
  50471. var x = sphere.center.x - this.origin.x;
  50472. var y = sphere.center.y - this.origin.y;
  50473. var z = sphere.center.z - this.origin.z;
  50474. var pyth = (x * x) + (y * y) + (z * z);
  50475. var rr = sphere.radius * sphere.radius;
  50476. if (pyth <= rr) {
  50477. return true;
  50478. }
  50479. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  50480. if (dot < 0.0) {
  50481. return false;
  50482. }
  50483. var temp = pyth - (dot * dot);
  50484. return temp <= rr;
  50485. };
  50486. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  50487. if (!this._edge1) {
  50488. this._edge1 = BABYLON.Vector3.Zero();
  50489. this._edge2 = BABYLON.Vector3.Zero();
  50490. this._pvec = BABYLON.Vector3.Zero();
  50491. this._tvec = BABYLON.Vector3.Zero();
  50492. this._qvec = BABYLON.Vector3.Zero();
  50493. }
  50494. vertex1.subtractToRef(vertex0, this._edge1);
  50495. vertex2.subtractToRef(vertex0, this._edge2);
  50496. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  50497. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  50498. if (det === 0) {
  50499. return null;
  50500. }
  50501. var invdet = 1 / det;
  50502. this.origin.subtractToRef(vertex0, this._tvec);
  50503. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  50504. if (bu < 0 || bu > 1.0) {
  50505. return null;
  50506. }
  50507. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  50508. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  50509. if (bv < 0 || bu + bv > 1.0) {
  50510. return null;
  50511. }
  50512. //check if the distance is longer than the predefined length.
  50513. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  50514. if (distance > this.length) {
  50515. return null;
  50516. }
  50517. return new BABYLON.IntersectionInfo(bu, bv, distance);
  50518. };
  50519. Ray.prototype.intersectsPlane = function (plane) {
  50520. var distance;
  50521. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  50522. if (Math.abs(result1) < 9.99999997475243E-07) {
  50523. return null;
  50524. }
  50525. else {
  50526. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  50527. distance = (-plane.d - result2) / result1;
  50528. if (distance < 0.0) {
  50529. if (distance < -9.99999997475243E-07) {
  50530. return null;
  50531. }
  50532. else {
  50533. return 0;
  50534. }
  50535. }
  50536. return distance;
  50537. }
  50538. };
  50539. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  50540. var tm = BABYLON.Tmp.Matrix[0];
  50541. mesh.getWorldMatrix().invertToRef(tm);
  50542. if (this._tmpRay) {
  50543. Ray.TransformToRef(this, tm, this._tmpRay);
  50544. }
  50545. else {
  50546. this._tmpRay = Ray.Transform(this, tm);
  50547. }
  50548. return mesh.intersects(this._tmpRay, fastCheck);
  50549. };
  50550. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  50551. if (results) {
  50552. results.length = 0;
  50553. }
  50554. else {
  50555. results = [];
  50556. }
  50557. for (var i = 0; i < meshes.length; i++) {
  50558. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  50559. if (pickInfo.hit) {
  50560. results.push(pickInfo);
  50561. }
  50562. }
  50563. results.sort(this._comparePickingInfo);
  50564. return results;
  50565. };
  50566. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  50567. if (pickingInfoA.distance < pickingInfoB.distance) {
  50568. return -1;
  50569. }
  50570. else if (pickingInfoA.distance > pickingInfoB.distance) {
  50571. return 1;
  50572. }
  50573. else {
  50574. return 0;
  50575. }
  50576. };
  50577. /**
  50578. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  50579. * @param sega the first point of the segment to test the intersection against
  50580. * @param segb the second point of the segment to test the intersection against
  50581. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  50582. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  50583. */
  50584. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  50585. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  50586. var u = segb.subtract(sega);
  50587. var v = rsegb.subtract(this.origin);
  50588. var w = sega.subtract(this.origin);
  50589. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50590. var b = BABYLON.Vector3.Dot(u, v);
  50591. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50592. var d = BABYLON.Vector3.Dot(u, w);
  50593. var e = BABYLON.Vector3.Dot(v, w);
  50594. var D = a * c - b * b; // always >= 0
  50595. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50596. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50597. // compute the line parameters of the two closest points
  50598. if (D < Ray.smallnum) {
  50599. sN = 0.0; // force using point P0 on segment S1
  50600. sD = 1.0; // to prevent possible division by 0.0 later
  50601. tN = e;
  50602. tD = c;
  50603. }
  50604. else {
  50605. sN = (b * e - c * d);
  50606. tN = (a * e - b * d);
  50607. if (sN < 0.0) {
  50608. sN = 0.0;
  50609. tN = e;
  50610. tD = c;
  50611. }
  50612. else if (sN > sD) {
  50613. sN = sD;
  50614. tN = e + b;
  50615. tD = c;
  50616. }
  50617. }
  50618. if (tN < 0.0) {
  50619. tN = 0.0;
  50620. // recompute sc for this edge
  50621. if (-d < 0.0) {
  50622. sN = 0.0;
  50623. }
  50624. else if (-d > a)
  50625. sN = sD;
  50626. else {
  50627. sN = -d;
  50628. sD = a;
  50629. }
  50630. }
  50631. else if (tN > tD) {
  50632. tN = tD;
  50633. // recompute sc for this edge
  50634. if ((-d + b) < 0.0) {
  50635. sN = 0;
  50636. }
  50637. else if ((-d + b) > a) {
  50638. sN = sD;
  50639. }
  50640. else {
  50641. sN = (-d + b);
  50642. sD = a;
  50643. }
  50644. }
  50645. // finally do the division to get sc and tc
  50646. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50647. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50648. // get the difference of the two closest points
  50649. var qtc = v.multiplyByFloats(tc, tc, tc);
  50650. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50651. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50652. if (isIntersected) {
  50653. return qtc.length();
  50654. }
  50655. return -1;
  50656. };
  50657. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50658. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50659. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50660. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50661. this.direction.normalize();
  50662. return this;
  50663. };
  50664. // Statics
  50665. Ray.Zero = function () {
  50666. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50667. };
  50668. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50669. var result = Ray.Zero();
  50670. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50671. };
  50672. /**
  50673. * 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
  50674. * transformed to the given world matrix.
  50675. * @param origin The origin point
  50676. * @param end The end point
  50677. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50678. */
  50679. Ray.CreateNewFromTo = function (origin, end, world) {
  50680. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50681. var direction = end.subtract(origin);
  50682. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50683. direction.normalize();
  50684. return Ray.Transform(new Ray(origin, direction, length), world);
  50685. };
  50686. Ray.Transform = function (ray, matrix) {
  50687. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50688. Ray.TransformToRef(ray, matrix, result);
  50689. return result;
  50690. };
  50691. Ray.TransformToRef = function (ray, matrix, result) {
  50692. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50693. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50694. result.length = ray.length;
  50695. var dir = result.direction;
  50696. var len = dir.length();
  50697. if (!(len === 0 || len === 1)) {
  50698. var num = 1.0 / len;
  50699. dir.x *= num;
  50700. dir.y *= num;
  50701. dir.z *= num;
  50702. result.length *= len;
  50703. }
  50704. };
  50705. Ray.smallnum = 0.00000001;
  50706. Ray.rayl = 10e8;
  50707. return Ray;
  50708. }());
  50709. BABYLON.Ray = Ray;
  50710. })(BABYLON || (BABYLON = {}));
  50711. //# sourceMappingURL=babylon.ray.js.map
  50712. "use strict";
  50713. var BABYLON;
  50714. (function (BABYLON) {
  50715. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50716. if (boxMin.x > sphereCenter.x + sphereRadius)
  50717. return false;
  50718. if (sphereCenter.x - sphereRadius > boxMax.x)
  50719. return false;
  50720. if (boxMin.y > sphereCenter.y + sphereRadius)
  50721. return false;
  50722. if (sphereCenter.y - sphereRadius > boxMax.y)
  50723. return false;
  50724. if (boxMin.z > sphereCenter.z + sphereRadius)
  50725. return false;
  50726. if (sphereCenter.z - sphereRadius > boxMax.z)
  50727. return false;
  50728. return true;
  50729. };
  50730. var getLowestRoot = (function () {
  50731. var result = { root: 0, found: false };
  50732. return function (a, b, c, maxR) {
  50733. result.root = 0;
  50734. result.found = false;
  50735. var determinant = b * b - 4.0 * a * c;
  50736. if (determinant < 0)
  50737. return result;
  50738. var sqrtD = Math.sqrt(determinant);
  50739. var r1 = (-b - sqrtD) / (2.0 * a);
  50740. var r2 = (-b + sqrtD) / (2.0 * a);
  50741. if (r1 > r2) {
  50742. var temp = r2;
  50743. r2 = r1;
  50744. r1 = temp;
  50745. }
  50746. if (r1 > 0 && r1 < maxR) {
  50747. result.root = r1;
  50748. result.found = true;
  50749. return result;
  50750. }
  50751. if (r2 > 0 && r2 < maxR) {
  50752. result.root = r2;
  50753. result.found = true;
  50754. return result;
  50755. }
  50756. return result;
  50757. };
  50758. })();
  50759. var Collider = /** @class */ (function () {
  50760. function Collider() {
  50761. this._collisionPoint = BABYLON.Vector3.Zero();
  50762. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50763. this._tempVector = BABYLON.Vector3.Zero();
  50764. this._tempVector2 = BABYLON.Vector3.Zero();
  50765. this._tempVector3 = BABYLON.Vector3.Zero();
  50766. this._tempVector4 = BABYLON.Vector3.Zero();
  50767. this._edge = BABYLON.Vector3.Zero();
  50768. this._baseToVertex = BABYLON.Vector3.Zero();
  50769. this._destinationPoint = BABYLON.Vector3.Zero();
  50770. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50771. this._displacementVector = BABYLON.Vector3.Zero();
  50772. this._radius = BABYLON.Vector3.One();
  50773. this._retry = 0;
  50774. this._basePointWorld = BABYLON.Vector3.Zero();
  50775. this._velocityWorld = BABYLON.Vector3.Zero();
  50776. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50777. this._collisionMask = -1;
  50778. }
  50779. Object.defineProperty(Collider.prototype, "collisionMask", {
  50780. get: function () {
  50781. return this._collisionMask;
  50782. },
  50783. set: function (mask) {
  50784. this._collisionMask = !isNaN(mask) ? mask : -1;
  50785. },
  50786. enumerable: true,
  50787. configurable: true
  50788. });
  50789. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50790. /**
  50791. * Gets the plane normal used to compute the sliding response (in local space)
  50792. */
  50793. get: function () {
  50794. return this._slidePlaneNormal;
  50795. },
  50796. enumerable: true,
  50797. configurable: true
  50798. });
  50799. // Methods
  50800. Collider.prototype._initialize = function (source, dir, e) {
  50801. this._velocity = dir;
  50802. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50803. this._basePoint = source;
  50804. source.multiplyToRef(this._radius, this._basePointWorld);
  50805. dir.multiplyToRef(this._radius, this._velocityWorld);
  50806. this._velocityWorldLength = this._velocityWorld.length();
  50807. this._epsilon = e;
  50808. this.collisionFound = false;
  50809. };
  50810. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50811. pa.subtractToRef(point, this._tempVector);
  50812. pb.subtractToRef(point, this._tempVector2);
  50813. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50814. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50815. if (d < 0)
  50816. return false;
  50817. pc.subtractToRef(point, this._tempVector3);
  50818. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50819. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50820. if (d < 0)
  50821. return false;
  50822. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50823. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50824. return d >= 0;
  50825. };
  50826. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50827. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50828. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50829. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50830. return false;
  50831. }
  50832. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50833. return false;
  50834. return true;
  50835. };
  50836. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50837. var t0;
  50838. var embeddedInPlane = false;
  50839. //defensive programming, actually not needed.
  50840. if (!trianglePlaneArray) {
  50841. trianglePlaneArray = [];
  50842. }
  50843. if (!trianglePlaneArray[faceIndex]) {
  50844. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50845. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50846. }
  50847. var trianglePlane = trianglePlaneArray[faceIndex];
  50848. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50849. return;
  50850. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50851. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50852. if (normalDotVelocity == 0) {
  50853. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50854. return;
  50855. embeddedInPlane = true;
  50856. t0 = 0;
  50857. }
  50858. else {
  50859. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50860. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50861. if (t0 > t1) {
  50862. var temp = t1;
  50863. t1 = t0;
  50864. t0 = temp;
  50865. }
  50866. if (t0 > 1.0 || t1 < 0.0)
  50867. return;
  50868. if (t0 < 0)
  50869. t0 = 0;
  50870. if (t0 > 1.0)
  50871. t0 = 1.0;
  50872. }
  50873. this._collisionPoint.copyFromFloats(0, 0, 0);
  50874. var found = false;
  50875. var t = 1.0;
  50876. if (!embeddedInPlane) {
  50877. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50878. this._velocity.scaleToRef(t0, this._tempVector);
  50879. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50880. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50881. found = true;
  50882. t = t0;
  50883. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50884. }
  50885. }
  50886. if (!found) {
  50887. var velocitySquaredLength = this._velocity.lengthSquared();
  50888. var a = velocitySquaredLength;
  50889. this._basePoint.subtractToRef(p1, this._tempVector);
  50890. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50891. var c = this._tempVector.lengthSquared() - 1.0;
  50892. var lowestRoot = getLowestRoot(a, b, c, t);
  50893. if (lowestRoot.found) {
  50894. t = lowestRoot.root;
  50895. found = true;
  50896. this._collisionPoint.copyFrom(p1);
  50897. }
  50898. this._basePoint.subtractToRef(p2, this._tempVector);
  50899. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50900. c = this._tempVector.lengthSquared() - 1.0;
  50901. lowestRoot = getLowestRoot(a, b, c, t);
  50902. if (lowestRoot.found) {
  50903. t = lowestRoot.root;
  50904. found = true;
  50905. this._collisionPoint.copyFrom(p2);
  50906. }
  50907. this._basePoint.subtractToRef(p3, this._tempVector);
  50908. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50909. c = this._tempVector.lengthSquared() - 1.0;
  50910. lowestRoot = getLowestRoot(a, b, c, t);
  50911. if (lowestRoot.found) {
  50912. t = lowestRoot.root;
  50913. found = true;
  50914. this._collisionPoint.copyFrom(p3);
  50915. }
  50916. p2.subtractToRef(p1, this._edge);
  50917. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50918. var edgeSquaredLength = this._edge.lengthSquared();
  50919. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50920. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50921. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50922. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50923. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50924. lowestRoot = getLowestRoot(a, b, c, t);
  50925. if (lowestRoot.found) {
  50926. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50927. if (f >= 0.0 && f <= 1.0) {
  50928. t = lowestRoot.root;
  50929. found = true;
  50930. this._edge.scaleInPlace(f);
  50931. p1.addToRef(this._edge, this._collisionPoint);
  50932. }
  50933. }
  50934. p3.subtractToRef(p2, this._edge);
  50935. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50936. edgeSquaredLength = this._edge.lengthSquared();
  50937. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50938. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50939. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50940. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50941. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50942. lowestRoot = getLowestRoot(a, b, c, t);
  50943. if (lowestRoot.found) {
  50944. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50945. if (f >= 0.0 && f <= 1.0) {
  50946. t = lowestRoot.root;
  50947. found = true;
  50948. this._edge.scaleInPlace(f);
  50949. p2.addToRef(this._edge, this._collisionPoint);
  50950. }
  50951. }
  50952. p1.subtractToRef(p3, this._edge);
  50953. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50954. edgeSquaredLength = this._edge.lengthSquared();
  50955. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50956. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50957. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50958. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50959. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50960. lowestRoot = getLowestRoot(a, b, c, t);
  50961. if (lowestRoot.found) {
  50962. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50963. if (f >= 0.0 && f <= 1.0) {
  50964. t = lowestRoot.root;
  50965. found = true;
  50966. this._edge.scaleInPlace(f);
  50967. p3.addToRef(this._edge, this._collisionPoint);
  50968. }
  50969. }
  50970. }
  50971. if (found) {
  50972. var distToCollision = t * this._velocity.length();
  50973. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50974. if (!this.intersectionPoint) {
  50975. this.intersectionPoint = this._collisionPoint.clone();
  50976. }
  50977. else {
  50978. this.intersectionPoint.copyFrom(this._collisionPoint);
  50979. }
  50980. this._nearestDistance = distToCollision;
  50981. this.collisionFound = true;
  50982. }
  50983. }
  50984. };
  50985. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50986. for (var i = indexStart; i < indexEnd; i += 3) {
  50987. var p1 = pts[indices[i] - decal];
  50988. var p2 = pts[indices[i + 1] - decal];
  50989. var p3 = pts[indices[i + 2] - decal];
  50990. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50991. }
  50992. };
  50993. Collider.prototype._getResponse = function (pos, vel) {
  50994. pos.addToRef(vel, this._destinationPoint);
  50995. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50996. this._basePoint.addToRef(vel, pos);
  50997. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50998. this._slidePlaneNormal.normalize();
  50999. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  51000. pos.addInPlace(this._displacementVector);
  51001. this.intersectionPoint.addInPlace(this._displacementVector);
  51002. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  51003. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  51004. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  51005. };
  51006. return Collider;
  51007. }());
  51008. BABYLON.Collider = Collider;
  51009. })(BABYLON || (BABYLON = {}));
  51010. //# sourceMappingURL=babylon.collider.js.map
  51011. "use strict";
  51012. var BABYLON;
  51013. (function (BABYLON) {
  51014. //WebWorker code will be inserted to this variable.
  51015. BABYLON.CollisionWorker = "";
  51016. var WorkerTaskType;
  51017. (function (WorkerTaskType) {
  51018. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  51019. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  51020. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  51021. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  51022. var WorkerReplyType;
  51023. (function (WorkerReplyType) {
  51024. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  51025. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  51026. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  51027. var CollisionCoordinatorWorker = /** @class */ (function () {
  51028. function CollisionCoordinatorWorker() {
  51029. var _this = this;
  51030. this._scaledPosition = BABYLON.Vector3.Zero();
  51031. this._scaledVelocity = BABYLON.Vector3.Zero();
  51032. this.onMeshUpdated = function (transformNode) {
  51033. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  51034. };
  51035. this.onGeometryUpdated = function (geometry) {
  51036. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  51037. };
  51038. this._afterRender = function () {
  51039. if (!_this._init)
  51040. return;
  51041. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  51042. return;
  51043. }
  51044. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  51045. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  51046. if (_this._runningUpdated > 4) {
  51047. return;
  51048. }
  51049. ++_this._runningUpdated;
  51050. var payload = {
  51051. updatedMeshes: _this._addUpdateMeshesList,
  51052. updatedGeometries: _this._addUpdateGeometriesList,
  51053. removedGeometries: _this._toRemoveGeometryArray,
  51054. removedMeshes: _this._toRemoveMeshesArray
  51055. };
  51056. var message = {
  51057. payload: payload,
  51058. taskType: WorkerTaskType.UPDATE
  51059. };
  51060. var serializable = [];
  51061. for (var id in payload.updatedGeometries) {
  51062. if (payload.updatedGeometries.hasOwnProperty(id)) {
  51063. //prepare transferables
  51064. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  51065. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  51066. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  51067. }
  51068. }
  51069. _this._worker.postMessage(message, serializable);
  51070. _this._addUpdateMeshesList = {};
  51071. _this._addUpdateGeometriesList = {};
  51072. _this._toRemoveGeometryArray = [];
  51073. _this._toRemoveMeshesArray = [];
  51074. };
  51075. this._onMessageFromWorker = function (e) {
  51076. var returnData = e.data;
  51077. if (returnData.error != WorkerReplyType.SUCCESS) {
  51078. //TODO what errors can be returned from the worker?
  51079. BABYLON.Tools.Warn("error returned from worker!");
  51080. return;
  51081. }
  51082. switch (returnData.taskType) {
  51083. case WorkerTaskType.INIT:
  51084. _this._init = true;
  51085. //Update the worked with ALL of the scene's current state
  51086. _this._scene.meshes.forEach(function (mesh) {
  51087. _this.onMeshAdded(mesh);
  51088. });
  51089. _this._scene.getGeometries().forEach(function (geometry) {
  51090. _this.onGeometryAdded(geometry);
  51091. });
  51092. break;
  51093. case WorkerTaskType.UPDATE:
  51094. _this._runningUpdated--;
  51095. break;
  51096. case WorkerTaskType.COLLIDE:
  51097. var returnPayload = returnData.payload;
  51098. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  51099. return;
  51100. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  51101. if (callback) {
  51102. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  51103. if (mesh) {
  51104. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  51105. }
  51106. }
  51107. //cleanup
  51108. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  51109. break;
  51110. }
  51111. };
  51112. this._collisionsCallbackArray = [];
  51113. this._init = false;
  51114. this._runningUpdated = 0;
  51115. this._addUpdateMeshesList = {};
  51116. this._addUpdateGeometriesList = {};
  51117. this._toRemoveGeometryArray = [];
  51118. this._toRemoveMeshesArray = [];
  51119. }
  51120. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51121. if (!this._init)
  51122. return;
  51123. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  51124. return;
  51125. position.divideToRef(collider._radius, this._scaledPosition);
  51126. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51127. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  51128. var payload = {
  51129. collider: {
  51130. position: this._scaledPosition.asArray(),
  51131. velocity: this._scaledVelocity.asArray(),
  51132. radius: collider._radius.asArray()
  51133. },
  51134. collisionId: collisionIndex,
  51135. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  51136. maximumRetry: maximumRetry
  51137. };
  51138. var message = {
  51139. payload: payload,
  51140. taskType: WorkerTaskType.COLLIDE
  51141. };
  51142. this._worker.postMessage(message);
  51143. };
  51144. CollisionCoordinatorWorker.prototype.init = function (scene) {
  51145. this._scene = scene;
  51146. this._scene.registerAfterRender(this._afterRender);
  51147. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  51148. this._worker = new Worker(workerUrl);
  51149. this._worker.onmessage = this._onMessageFromWorker;
  51150. var message = {
  51151. payload: {},
  51152. taskType: WorkerTaskType.INIT
  51153. };
  51154. this._worker.postMessage(message);
  51155. };
  51156. CollisionCoordinatorWorker.prototype.destroy = function () {
  51157. this._scene.unregisterAfterRender(this._afterRender);
  51158. this._worker.terminate();
  51159. };
  51160. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  51161. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  51162. this.onMeshUpdated(mesh);
  51163. };
  51164. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  51165. this._toRemoveMeshesArray.push(mesh.uniqueId);
  51166. };
  51167. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  51168. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  51169. geometry.onGeometryUpdated = this.onGeometryUpdated;
  51170. this.onGeometryUpdated(geometry);
  51171. };
  51172. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  51173. this._toRemoveGeometryArray.push(geometry.id);
  51174. };
  51175. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  51176. var submeshes = [];
  51177. if (mesh.subMeshes) {
  51178. submeshes = mesh.subMeshes.map(function (sm, idx) {
  51179. var boundingInfo = sm.getBoundingInfo();
  51180. return {
  51181. position: idx,
  51182. verticesStart: sm.verticesStart,
  51183. verticesCount: sm.verticesCount,
  51184. indexStart: sm.indexStart,
  51185. indexCount: sm.indexCount,
  51186. hasMaterial: !!sm.getMaterial(),
  51187. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51188. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51189. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51190. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  51191. };
  51192. });
  51193. }
  51194. var geometryId = null;
  51195. if (mesh instanceof BABYLON.Mesh) {
  51196. var geometry = mesh.geometry;
  51197. geometryId = geometry ? geometry.id : null;
  51198. }
  51199. else if (mesh instanceof BABYLON.InstancedMesh) {
  51200. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  51201. geometryId = geometry ? geometry.id : null;
  51202. }
  51203. var boundingInfo = mesh.getBoundingInfo();
  51204. return {
  51205. uniqueId: mesh.uniqueId,
  51206. id: mesh.id,
  51207. name: mesh.name,
  51208. geometryId: geometryId,
  51209. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51210. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51211. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51212. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  51213. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  51214. subMeshes: submeshes,
  51215. checkCollisions: mesh.checkCollisions
  51216. };
  51217. };
  51218. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  51219. return {
  51220. id: geometry.id,
  51221. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  51222. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  51223. indices: new Uint32Array(geometry.getIndices() || []),
  51224. };
  51225. };
  51226. return CollisionCoordinatorWorker;
  51227. }());
  51228. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  51229. var CollisionCoordinatorLegacy = /** @class */ (function () {
  51230. function CollisionCoordinatorLegacy() {
  51231. this._scaledPosition = BABYLON.Vector3.Zero();
  51232. this._scaledVelocity = BABYLON.Vector3.Zero();
  51233. this._finalPosition = BABYLON.Vector3.Zero();
  51234. }
  51235. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51236. position.divideToRef(collider._radius, this._scaledPosition);
  51237. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51238. collider.collidedMesh = null;
  51239. collider._retry = 0;
  51240. collider._initialVelocity = this._scaledVelocity;
  51241. collider._initialPosition = this._scaledPosition;
  51242. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  51243. this._finalPosition.multiplyInPlace(collider._radius);
  51244. //run the callback
  51245. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  51246. };
  51247. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  51248. this._scene = scene;
  51249. };
  51250. CollisionCoordinatorLegacy.prototype.destroy = function () {
  51251. //Legacy need no destruction method.
  51252. };
  51253. //No update in legacy mode
  51254. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  51255. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  51256. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  51257. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  51258. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  51259. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  51260. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  51261. if (excludedMesh === void 0) { excludedMesh = null; }
  51262. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  51263. if (collider._retry >= maximumRetry) {
  51264. finalPosition.copyFrom(position);
  51265. return;
  51266. }
  51267. // Check if this is a mesh else camera or -1
  51268. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  51269. collider._initialize(position, velocity, closeDistance);
  51270. // Check all meshes
  51271. for (var index = 0; index < this._scene.meshes.length; index++) {
  51272. var mesh = this._scene.meshes[index];
  51273. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  51274. mesh._checkCollision(collider);
  51275. }
  51276. }
  51277. if (!collider.collisionFound) {
  51278. position.addToRef(velocity, finalPosition);
  51279. return;
  51280. }
  51281. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  51282. collider._getResponse(position, velocity);
  51283. }
  51284. if (velocity.length() <= closeDistance) {
  51285. finalPosition.copyFrom(position);
  51286. return;
  51287. }
  51288. collider._retry++;
  51289. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  51290. };
  51291. return CollisionCoordinatorLegacy;
  51292. }());
  51293. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  51294. })(BABYLON || (BABYLON = {}));
  51295. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  51296. "use strict";
  51297. var BABYLON;
  51298. (function (BABYLON) {
  51299. /**
  51300. * A particle represents one of the element emitted by a particle system.
  51301. * This is mainly define by its coordinates, direction, velocity and age.
  51302. */
  51303. var Particle = /** @class */ (function () {
  51304. /**
  51305. * Creates a new instance of @see Particle
  51306. * @param particleSystem the particle system the particle belongs to
  51307. */
  51308. function Particle(
  51309. /**
  51310. * particleSystem the particle system the particle belongs to.
  51311. */
  51312. particleSystem) {
  51313. this.particleSystem = particleSystem;
  51314. /**
  51315. * The world position of the particle in the scene.
  51316. */
  51317. this.position = BABYLON.Vector3.Zero();
  51318. /**
  51319. * The world direction of the particle in the scene.
  51320. */
  51321. this.direction = BABYLON.Vector3.Zero();
  51322. /**
  51323. * The color of the particle.
  51324. */
  51325. this.color = new BABYLON.Color4(0, 0, 0, 0);
  51326. /**
  51327. * The color change of the particle per step.
  51328. */
  51329. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  51330. /**
  51331. * Defines how long will the life of the particle be.
  51332. */
  51333. this.lifeTime = 1.0;
  51334. /**
  51335. * The current age of the particle.
  51336. */
  51337. this.age = 0;
  51338. /**
  51339. * The current size of the particle.
  51340. */
  51341. this.size = 0;
  51342. /**
  51343. * The current angle of the particle.
  51344. */
  51345. this.angle = 0;
  51346. /**
  51347. * Defines how fast is the angle changing.
  51348. */
  51349. this.angularSpeed = 0;
  51350. /**
  51351. * Defines the cell index used by the particle to be rendered from a sprite.
  51352. */
  51353. this.cellIndex = 0;
  51354. this._currentFrameCounter = 0;
  51355. if (!this.particleSystem.isAnimationSheetEnabled) {
  51356. return;
  51357. }
  51358. this.updateCellInfoFromSystem();
  51359. }
  51360. Particle.prototype.updateCellInfoFromSystem = function () {
  51361. this.cellIndex = this.particleSystem.startSpriteCellID;
  51362. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  51363. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  51364. }
  51365. else {
  51366. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  51367. }
  51368. };
  51369. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  51370. // (ageOffset / scaledUpdateSpeed) / available cells
  51371. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  51372. this._currentFrameCounter += scaledUpdateSpeed;
  51373. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  51374. this._currentFrameCounter = 0;
  51375. this.cellIndex++;
  51376. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51377. this.cellIndex = this.particleSystem.endSpriteCellID;
  51378. }
  51379. }
  51380. };
  51381. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  51382. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  51383. this.cellIndex++;
  51384. this._currentFrameCounter = 0;
  51385. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51386. if (this.particleSystem.spriteCellLoop) {
  51387. this.cellIndex = this.particleSystem.startSpriteCellID;
  51388. }
  51389. else {
  51390. this.cellIndex = this.particleSystem.endSpriteCellID;
  51391. }
  51392. }
  51393. }
  51394. else {
  51395. this._currentFrameCounter++;
  51396. }
  51397. };
  51398. /**
  51399. * Copy the properties of particle to another one.
  51400. * @param other the particle to copy the information to.
  51401. */
  51402. Particle.prototype.copyTo = function (other) {
  51403. other.position.copyFrom(this.position);
  51404. other.direction.copyFrom(this.direction);
  51405. other.color.copyFrom(this.color);
  51406. other.colorStep.copyFrom(this.colorStep);
  51407. other.lifeTime = this.lifeTime;
  51408. other.age = this.age;
  51409. other.size = this.size;
  51410. other.angle = this.angle;
  51411. other.angularSpeed = this.angularSpeed;
  51412. other.particleSystem = this.particleSystem;
  51413. other.cellIndex = this.cellIndex;
  51414. };
  51415. return Particle;
  51416. }());
  51417. BABYLON.Particle = Particle;
  51418. })(BABYLON || (BABYLON = {}));
  51419. //# sourceMappingURL=babylon.particle.js.map
  51420. "use strict";
  51421. var BABYLON;
  51422. (function (BABYLON) {
  51423. /**
  51424. * This represents a particle system in Babylon.
  51425. * 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.
  51426. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  51427. * @example https://doc.babylonjs.com/babylon101/particles
  51428. */
  51429. var ParticleSystem = /** @class */ (function () {
  51430. /**
  51431. * Instantiates a particle system.
  51432. * 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.
  51433. * @param name The name of the particle system
  51434. * @param capacity The max number of particles alive at the same time
  51435. * @param scene The scene the particle system belongs to
  51436. * @param customEffect a custom effect used to change the way particles are rendered by default
  51437. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  51438. * @param epsilon Offset used to render the particles
  51439. */
  51440. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  51441. if (customEffect === void 0) { customEffect = null; }
  51442. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  51443. if (epsilon === void 0) { epsilon = 0.01; }
  51444. var _this = this;
  51445. /**
  51446. * List of animations used by the particle system.
  51447. */
  51448. this.animations = [];
  51449. /**
  51450. * The rendering group used by the Particle system to chose when to render.
  51451. */
  51452. this.renderingGroupId = 0;
  51453. /**
  51454. * The emitter represents the Mesh or position we are attaching the particle system to.
  51455. */
  51456. this.emitter = null;
  51457. /**
  51458. * The maximum number of particles to emit per frame
  51459. */
  51460. this.emitRate = 10;
  51461. /**
  51462. * If you want to launch only a few particles at once, that can be done, as well.
  51463. */
  51464. this.manualEmitCount = -1;
  51465. /**
  51466. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51467. */
  51468. this.updateSpeed = 0.01;
  51469. /**
  51470. * The amount of time the particle system is running (depends of the overall update speed).
  51471. */
  51472. this.targetStopDuration = 0;
  51473. /**
  51474. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  51475. */
  51476. this.disposeOnStop = false;
  51477. /**
  51478. * Minimum power of emitting particles.
  51479. */
  51480. this.minEmitPower = 1;
  51481. /**
  51482. * Maximum power of emitting particles.
  51483. */
  51484. this.maxEmitPower = 1;
  51485. /**
  51486. * Minimum life time of emitting particles.
  51487. */
  51488. this.minLifeTime = 1;
  51489. /**
  51490. * Maximum life time of emitting particles.
  51491. */
  51492. this.maxLifeTime = 1;
  51493. /**
  51494. * Minimum Size of emitting particles.
  51495. */
  51496. this.minSize = 1;
  51497. /**
  51498. * Maximum Size of emitting particles.
  51499. */
  51500. this.maxSize = 1;
  51501. /**
  51502. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  51503. */
  51504. this.minAngularSpeed = 0;
  51505. /**
  51506. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  51507. */
  51508. this.maxAngularSpeed = 0;
  51509. /**
  51510. * The layer mask we are rendering the particles through.
  51511. */
  51512. this.layerMask = 0x0FFFFFFF;
  51513. /**
  51514. * This can help using your own shader to render the particle system.
  51515. * The according effect will be created
  51516. */
  51517. this.customShader = null;
  51518. /**
  51519. * By default particle system starts as soon as they are created. This prevents the
  51520. * automatic start to happen and let you decide when to start emitting particles.
  51521. */
  51522. this.preventAutoStart = false;
  51523. /**
  51524. * Callback triggered when the particle animation is ending.
  51525. */
  51526. this.onAnimationEnd = null;
  51527. /**
  51528. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51529. */
  51530. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  51531. /**
  51532. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  51533. * to override the particles.
  51534. */
  51535. this.forceDepthWrite = false;
  51536. /**
  51537. * You can use gravity if you want to give an orientation to your particles.
  51538. */
  51539. this.gravity = BABYLON.Vector3.Zero();
  51540. /**
  51541. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51542. */
  51543. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51544. /**
  51545. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51546. */
  51547. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51548. /**
  51549. * Color the particle will have at the end of its lifetime.
  51550. */
  51551. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  51552. /**
  51553. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  51554. */
  51555. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51556. /**
  51557. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  51558. */
  51559. this.spriteCellLoop = true;
  51560. /**
  51561. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  51562. */
  51563. this.spriteCellChangeSpeed = 0;
  51564. /**
  51565. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  51566. */
  51567. this.startSpriteCellID = 0;
  51568. /**
  51569. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  51570. */
  51571. this.endSpriteCellID = 0;
  51572. /**
  51573. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  51574. */
  51575. this.spriteCellWidth = 0;
  51576. /**
  51577. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  51578. */
  51579. this.spriteCellHeight = 0;
  51580. /**
  51581. * An event triggered when the system is disposed.
  51582. */
  51583. this.onDisposeObservable = new BABYLON.Observable();
  51584. this._particles = new Array();
  51585. this._stockParticles = new Array();
  51586. this._newPartsExcess = 0;
  51587. this._vertexBuffers = {};
  51588. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  51589. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  51590. this._scaledDirection = BABYLON.Vector3.Zero();
  51591. this._scaledGravity = BABYLON.Vector3.Zero();
  51592. this._currentRenderId = -1;
  51593. this._started = false;
  51594. this._stopped = false;
  51595. this._actualFrame = 0;
  51596. this._vertexBufferSize = 11;
  51597. // start of sub system methods
  51598. /**
  51599. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51600. * Its lifetime will start back at 0.
  51601. */
  51602. this.recycleParticle = function (particle) {
  51603. var lastParticle = _this._particles.pop();
  51604. if (lastParticle !== particle) {
  51605. lastParticle.copyTo(particle);
  51606. }
  51607. _this._stockParticles.push(lastParticle);
  51608. };
  51609. this._createParticle = function () {
  51610. var particle;
  51611. if (_this._stockParticles.length !== 0) {
  51612. particle = _this._stockParticles.pop();
  51613. particle.age = 0;
  51614. particle.cellIndex = _this.startSpriteCellID;
  51615. }
  51616. else {
  51617. particle = new BABYLON.Particle(_this);
  51618. }
  51619. return particle;
  51620. };
  51621. this._emitFromParticle = function (particle) {
  51622. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  51623. return;
  51624. }
  51625. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  51626. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  51627. subSystem._rootParticleSystem = _this;
  51628. _this.activeSubSystems.push(subSystem);
  51629. subSystem.start();
  51630. };
  51631. this._appendParticleVertexes = null;
  51632. this.id = name;
  51633. this.name = name;
  51634. this._capacity = capacity;
  51635. this._epsilon = epsilon;
  51636. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51637. if (isAnimationSheetEnabled) {
  51638. this._vertexBufferSize = 12;
  51639. }
  51640. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51641. this._customEffect = customEffect;
  51642. scene.particleSystems.push(this);
  51643. this._createIndexBuffer();
  51644. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51645. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51646. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51647. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51648. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51649. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51650. if (this._isAnimationSheetEnabled) {
  51651. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51652. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51653. }
  51654. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51655. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51656. this._vertexBuffers["options"] = options;
  51657. // Default emitter type
  51658. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51659. this.updateFunction = function (particles) {
  51660. for (var index = 0; index < particles.length; index++) {
  51661. var particle = particles[index];
  51662. particle.age += _this._scaledUpdateSpeed;
  51663. if (particle.age >= particle.lifeTime) {
  51664. _this._emitFromParticle(particle);
  51665. _this.recycleParticle(particle);
  51666. index--;
  51667. continue;
  51668. }
  51669. else {
  51670. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51671. particle.color.addInPlace(_this._scaledColorStep);
  51672. if (particle.color.a < 0)
  51673. particle.color.a = 0;
  51674. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51675. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51676. particle.position.addInPlace(_this._scaledDirection);
  51677. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51678. particle.direction.addInPlace(_this._scaledGravity);
  51679. if (_this._isAnimationSheetEnabled) {
  51680. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51681. }
  51682. }
  51683. }
  51684. };
  51685. }
  51686. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51687. /**
  51688. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51689. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51690. */
  51691. get: function () {
  51692. if (this.particleEmitterType.direction1) {
  51693. return this.particleEmitterType.direction1;
  51694. }
  51695. return BABYLON.Vector3.Zero();
  51696. },
  51697. set: function (value) {
  51698. if (this.particleEmitterType.direction1) {
  51699. this.particleEmitterType.direction1 = value;
  51700. }
  51701. },
  51702. enumerable: true,
  51703. configurable: true
  51704. });
  51705. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51706. /**
  51707. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51708. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51709. */
  51710. get: function () {
  51711. if (this.particleEmitterType.direction2) {
  51712. return this.particleEmitterType.direction2;
  51713. }
  51714. return BABYLON.Vector3.Zero();
  51715. },
  51716. set: function (value) {
  51717. if (this.particleEmitterType.direction2) {
  51718. this.particleEmitterType.direction2 = value;
  51719. }
  51720. },
  51721. enumerable: true,
  51722. configurable: true
  51723. });
  51724. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51725. /**
  51726. * 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.
  51727. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51728. */
  51729. get: function () {
  51730. if (this.particleEmitterType.minEmitBox) {
  51731. return this.particleEmitterType.minEmitBox;
  51732. }
  51733. return BABYLON.Vector3.Zero();
  51734. },
  51735. set: function (value) {
  51736. if (this.particleEmitterType.minEmitBox) {
  51737. this.particleEmitterType.minEmitBox = value;
  51738. }
  51739. },
  51740. enumerable: true,
  51741. configurable: true
  51742. });
  51743. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51744. /**
  51745. * 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.
  51746. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51747. */
  51748. get: function () {
  51749. if (this.particleEmitterType.maxEmitBox) {
  51750. return this.particleEmitterType.maxEmitBox;
  51751. }
  51752. return BABYLON.Vector3.Zero();
  51753. },
  51754. set: function (value) {
  51755. if (this.particleEmitterType.maxEmitBox) {
  51756. this.particleEmitterType.maxEmitBox = value;
  51757. }
  51758. },
  51759. enumerable: true,
  51760. configurable: true
  51761. });
  51762. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51763. /**
  51764. * Sets a callback that will be triggered when the system is disposed.
  51765. */
  51766. set: function (callback) {
  51767. if (this._onDisposeObserver) {
  51768. this.onDisposeObservable.remove(this._onDisposeObserver);
  51769. }
  51770. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51771. },
  51772. enumerable: true,
  51773. configurable: true
  51774. });
  51775. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51776. /**
  51777. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51778. */
  51779. get: function () {
  51780. return this._isAnimationSheetEnabled;
  51781. },
  51782. enumerable: true,
  51783. configurable: true
  51784. });
  51785. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51786. //end of Sub-emitter
  51787. /**
  51788. * Gets the current list of active particles
  51789. */
  51790. get: function () {
  51791. return this._particles;
  51792. },
  51793. enumerable: true,
  51794. configurable: true
  51795. });
  51796. /**
  51797. * Returns the string "ParticleSystem"
  51798. * @returns a string containing the class name
  51799. */
  51800. ParticleSystem.prototype.getClassName = function () {
  51801. return "ParticleSystem";
  51802. };
  51803. ParticleSystem.prototype._createIndexBuffer = function () {
  51804. var indices = [];
  51805. var index = 0;
  51806. for (var count = 0; count < this._capacity; count++) {
  51807. indices.push(index);
  51808. indices.push(index + 1);
  51809. indices.push(index + 2);
  51810. indices.push(index);
  51811. indices.push(index + 2);
  51812. indices.push(index + 3);
  51813. index += 4;
  51814. }
  51815. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51816. };
  51817. /**
  51818. * Gets the maximum number of particles active at the same time.
  51819. * @returns The max number of active particles.
  51820. */
  51821. ParticleSystem.prototype.getCapacity = function () {
  51822. return this._capacity;
  51823. };
  51824. /**
  51825. * Gets Wether there are still active particles in the system.
  51826. * @returns True if it is alive, otherwise false.
  51827. */
  51828. ParticleSystem.prototype.isAlive = function () {
  51829. return this._alive;
  51830. };
  51831. /**
  51832. * Gets Wether the system has been started.
  51833. * @returns True if it has been started, otherwise false.
  51834. */
  51835. ParticleSystem.prototype.isStarted = function () {
  51836. return this._started;
  51837. };
  51838. /**
  51839. * Starts the particle system and begins to emit.
  51840. */
  51841. ParticleSystem.prototype.start = function () {
  51842. this._started = true;
  51843. this._stopped = false;
  51844. this._actualFrame = 0;
  51845. if (this.subEmitters && this.subEmitters.length != 0) {
  51846. this.activeSubSystems = new Array();
  51847. }
  51848. };
  51849. /**
  51850. * Stops the particle system.
  51851. * @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.
  51852. */
  51853. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  51854. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  51855. this._stopped = true;
  51856. if (stopSubEmitters) {
  51857. this._stopSubEmitters();
  51858. }
  51859. };
  51860. // animation sheet
  51861. /**
  51862. * Remove all active particles
  51863. */
  51864. ParticleSystem.prototype.reset = function () {
  51865. this._stockParticles = [];
  51866. this._particles = [];
  51867. };
  51868. /**
  51869. * @ignore (for internal use only)
  51870. */
  51871. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51872. var offset = index * this._vertexBufferSize;
  51873. this._vertexData[offset] = particle.position.x;
  51874. this._vertexData[offset + 1] = particle.position.y;
  51875. this._vertexData[offset + 2] = particle.position.z;
  51876. this._vertexData[offset + 3] = particle.color.r;
  51877. this._vertexData[offset + 4] = particle.color.g;
  51878. this._vertexData[offset + 5] = particle.color.b;
  51879. this._vertexData[offset + 6] = particle.color.a;
  51880. this._vertexData[offset + 7] = particle.angle;
  51881. this._vertexData[offset + 8] = particle.size;
  51882. this._vertexData[offset + 9] = offsetX;
  51883. this._vertexData[offset + 10] = offsetY;
  51884. };
  51885. /**
  51886. * @ignore (for internal use only)
  51887. */
  51888. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51889. if (offsetX === 0)
  51890. offsetX = this._epsilon;
  51891. else if (offsetX === 1)
  51892. offsetX = 1 - this._epsilon;
  51893. if (offsetY === 0)
  51894. offsetY = this._epsilon;
  51895. else if (offsetY === 1)
  51896. offsetY = 1 - this._epsilon;
  51897. var offset = index * this._vertexBufferSize;
  51898. this._vertexData[offset] = particle.position.x;
  51899. this._vertexData[offset + 1] = particle.position.y;
  51900. this._vertexData[offset + 2] = particle.position.z;
  51901. this._vertexData[offset + 3] = particle.color.r;
  51902. this._vertexData[offset + 4] = particle.color.g;
  51903. this._vertexData[offset + 5] = particle.color.b;
  51904. this._vertexData[offset + 6] = particle.color.a;
  51905. this._vertexData[offset + 7] = particle.angle;
  51906. this._vertexData[offset + 8] = particle.size;
  51907. this._vertexData[offset + 9] = offsetX;
  51908. this._vertexData[offset + 10] = offsetY;
  51909. this._vertexData[offset + 11] = particle.cellIndex;
  51910. };
  51911. ParticleSystem.prototype._stopSubEmitters = function () {
  51912. if (!this.activeSubSystems) {
  51913. return;
  51914. }
  51915. this.activeSubSystems.forEach(function (subSystem) {
  51916. subSystem.stop(true);
  51917. });
  51918. this.activeSubSystems = new Array();
  51919. };
  51920. ParticleSystem.prototype._removeFromRoot = function () {
  51921. if (!this._rootParticleSystem) {
  51922. return;
  51923. }
  51924. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  51925. if (index !== -1) {
  51926. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  51927. }
  51928. };
  51929. // end of sub system methods
  51930. ParticleSystem.prototype._update = function (newParticles) {
  51931. // Update current
  51932. this._alive = this._particles.length > 0;
  51933. this.updateFunction(this._particles);
  51934. // Add new ones
  51935. var worldMatrix;
  51936. if (this.emitter.position) {
  51937. var emitterMesh = this.emitter;
  51938. worldMatrix = emitterMesh.getWorldMatrix();
  51939. }
  51940. else {
  51941. var emitterPosition = this.emitter;
  51942. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51943. }
  51944. var particle;
  51945. for (var index = 0; index < newParticles; index++) {
  51946. if (this._particles.length === this._capacity) {
  51947. break;
  51948. }
  51949. particle = this._createParticle();
  51950. this._particles.push(particle);
  51951. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51952. if (this.startPositionFunction) {
  51953. this.startPositionFunction(worldMatrix, particle.position, particle);
  51954. }
  51955. else {
  51956. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51957. }
  51958. if (this.startDirectionFunction) {
  51959. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51960. }
  51961. else {
  51962. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51963. }
  51964. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51965. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51966. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51967. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51968. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51969. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51970. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51971. }
  51972. };
  51973. ParticleSystem.prototype._getEffect = function () {
  51974. if (this._customEffect) {
  51975. return this._customEffect;
  51976. }
  51977. ;
  51978. var defines = [];
  51979. if (this._scene.clipPlane) {
  51980. defines.push("#define CLIPPLANE");
  51981. }
  51982. if (this._isAnimationSheetEnabled) {
  51983. defines.push("#define ANIMATESHEET");
  51984. }
  51985. // Effect
  51986. var join = defines.join("\n");
  51987. if (this._cachedDefines !== join) {
  51988. this._cachedDefines = join;
  51989. var attributesNamesOrOptions;
  51990. var effectCreationOption;
  51991. if (this._isAnimationSheetEnabled) {
  51992. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51993. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51994. }
  51995. else {
  51996. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51997. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51998. }
  51999. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  52000. }
  52001. return this._effect;
  52002. };
  52003. /**
  52004. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52005. */
  52006. ParticleSystem.prototype.animate = function () {
  52007. if (!this._started)
  52008. return;
  52009. var effect = this._getEffect();
  52010. // Check
  52011. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  52012. return;
  52013. if (this._currentRenderId === this._scene.getRenderId()) {
  52014. return;
  52015. }
  52016. this._currentRenderId = this._scene.getRenderId();
  52017. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  52018. // determine the number of particles we need to create
  52019. var newParticles;
  52020. if (this.manualEmitCount > -1) {
  52021. newParticles = this.manualEmitCount;
  52022. this._newPartsExcess = 0;
  52023. this.manualEmitCount = 0;
  52024. }
  52025. else {
  52026. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  52027. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  52028. }
  52029. if (this._newPartsExcess > 1.0) {
  52030. newParticles += this._newPartsExcess >> 0;
  52031. this._newPartsExcess -= this._newPartsExcess >> 0;
  52032. }
  52033. this._alive = false;
  52034. if (!this._stopped) {
  52035. this._actualFrame += this._scaledUpdateSpeed;
  52036. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52037. this.stop();
  52038. }
  52039. else {
  52040. newParticles = 0;
  52041. }
  52042. this._update(newParticles);
  52043. // Stopped?
  52044. if (this._stopped) {
  52045. if (!this._alive) {
  52046. this._started = false;
  52047. if (this.onAnimationEnd) {
  52048. this.onAnimationEnd();
  52049. }
  52050. if (this.disposeOnStop) {
  52051. this._scene._toBeDisposed.push(this);
  52052. }
  52053. }
  52054. }
  52055. // Animation sheet
  52056. if (this._isAnimationSheetEnabled) {
  52057. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  52058. }
  52059. else {
  52060. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  52061. }
  52062. // Update VBO
  52063. var offset = 0;
  52064. for (var index = 0; index < this._particles.length; index++) {
  52065. var particle = this._particles[index];
  52066. this._appendParticleVertexes(offset, particle);
  52067. offset += 4;
  52068. }
  52069. if (this._vertexBuffer) {
  52070. this._vertexBuffer.update(this._vertexData);
  52071. }
  52072. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  52073. this.stop();
  52074. }
  52075. };
  52076. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  52077. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  52078. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  52079. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  52080. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  52081. };
  52082. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  52083. this._appendParticleVertex(offset++, particle, 0, 0);
  52084. this._appendParticleVertex(offset++, particle, 1, 0);
  52085. this._appendParticleVertex(offset++, particle, 1, 1);
  52086. this._appendParticleVertex(offset++, particle, 0, 1);
  52087. };
  52088. /**
  52089. * Rebuilds the particle system.
  52090. */
  52091. ParticleSystem.prototype.rebuild = function () {
  52092. this._createIndexBuffer();
  52093. if (this._vertexBuffer) {
  52094. this._vertexBuffer._rebuild();
  52095. }
  52096. };
  52097. /**
  52098. * Is this system ready to be used/rendered
  52099. * @return true if the system is ready
  52100. */
  52101. ParticleSystem.prototype.isReady = function () {
  52102. var effect = this._getEffect();
  52103. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  52104. return false;
  52105. }
  52106. return true;
  52107. };
  52108. /**
  52109. * Renders the particle system in its current state.
  52110. * @returns the current number of particles
  52111. */
  52112. ParticleSystem.prototype.render = function () {
  52113. var effect = this._getEffect();
  52114. // Check
  52115. if (!this.isReady() || !this._particles.length) {
  52116. return 0;
  52117. }
  52118. var engine = this._scene.getEngine();
  52119. // Render
  52120. engine.enableEffect(effect);
  52121. engine.setState(false);
  52122. var viewMatrix = this._scene.getViewMatrix();
  52123. effect.setTexture("diffuseSampler", this.particleTexture);
  52124. effect.setMatrix("view", viewMatrix);
  52125. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  52126. if (this._isAnimationSheetEnabled && this.particleTexture) {
  52127. var baseSize = this.particleTexture.getBaseSize();
  52128. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  52129. }
  52130. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  52131. if (this._scene.clipPlane) {
  52132. var clipPlane = this._scene.clipPlane;
  52133. var invView = viewMatrix.clone();
  52134. invView.invert();
  52135. effect.setMatrix("invView", invView);
  52136. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52137. }
  52138. // VBOs
  52139. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  52140. // Draw order
  52141. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  52142. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52143. }
  52144. else {
  52145. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52146. }
  52147. if (this.forceDepthWrite) {
  52148. engine.setDepthWrite(true);
  52149. }
  52150. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  52151. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52152. return this._particles.length;
  52153. };
  52154. /**
  52155. * Disposes the particle system and free the associated resources
  52156. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52157. */
  52158. ParticleSystem.prototype.dispose = function (disposeTexture) {
  52159. if (disposeTexture === void 0) { disposeTexture = true; }
  52160. if (this._vertexBuffer) {
  52161. this._vertexBuffer.dispose();
  52162. this._vertexBuffer = null;
  52163. }
  52164. if (this._indexBuffer) {
  52165. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52166. this._indexBuffer = null;
  52167. }
  52168. if (disposeTexture && this.particleTexture) {
  52169. this.particleTexture.dispose();
  52170. this.particleTexture = null;
  52171. }
  52172. this._removeFromRoot();
  52173. // Remove from scene
  52174. var index = this._scene.particleSystems.indexOf(this);
  52175. if (index > -1) {
  52176. this._scene.particleSystems.splice(index, 1);
  52177. }
  52178. // Callback
  52179. this.onDisposeObservable.notifyObservers(this);
  52180. this.onDisposeObservable.clear();
  52181. };
  52182. /**
  52183. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  52184. * @param radius The radius of the sphere to emit from
  52185. * @returns the emitter
  52186. */
  52187. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  52188. if (radius === void 0) { radius = 1; }
  52189. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  52190. this.particleEmitterType = particleEmitter;
  52191. return particleEmitter;
  52192. };
  52193. /**
  52194. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  52195. * @param radius The radius of the sphere to emit from
  52196. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  52197. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  52198. * @returns the emitter
  52199. */
  52200. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  52201. if (radius === void 0) { radius = 1; }
  52202. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  52203. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  52204. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  52205. this.particleEmitterType = particleEmitter;
  52206. return particleEmitter;
  52207. };
  52208. /**
  52209. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  52210. * @param radius The radius of the cone to emit from
  52211. * @param angle The base angle of the cone
  52212. * @returns the emitter
  52213. */
  52214. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  52215. if (radius === void 0) { radius = 1; }
  52216. if (angle === void 0) { angle = Math.PI / 4; }
  52217. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  52218. this.particleEmitterType = particleEmitter;
  52219. return particleEmitter;
  52220. };
  52221. // 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.
  52222. /**
  52223. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  52224. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  52225. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  52226. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52227. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52228. * @returns the emitter
  52229. */
  52230. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  52231. var particleEmitter = new BABYLON.BoxParticleEmitter();
  52232. this.direction1 = direction1;
  52233. this.direction2 = direction2;
  52234. this.minEmitBox = minEmitBox;
  52235. this.maxEmitBox = maxEmitBox;
  52236. this.particleEmitterType = particleEmitter;
  52237. return particleEmitter;
  52238. };
  52239. // Clone
  52240. /**
  52241. * Clones the particle system.
  52242. * @param name The name of the cloned object
  52243. * @param newEmitter The new emitter to use
  52244. * @returns the cloned particle system
  52245. */
  52246. ParticleSystem.prototype.clone = function (name, newEmitter) {
  52247. var custom = null;
  52248. var program = null;
  52249. if (this.customShader != null) {
  52250. program = this.customShader;
  52251. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52252. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52253. }
  52254. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  52255. result.customShader = program;
  52256. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  52257. if (newEmitter === undefined) {
  52258. newEmitter = this.emitter;
  52259. }
  52260. result.emitter = newEmitter;
  52261. if (this.particleTexture) {
  52262. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52263. }
  52264. if (!this.preventAutoStart) {
  52265. result.start();
  52266. }
  52267. return result;
  52268. };
  52269. /**
  52270. * Serializes the particle system to a JSON object.
  52271. * @returns the JSON object
  52272. */
  52273. ParticleSystem.prototype.serialize = function () {
  52274. var serializationObject = {};
  52275. serializationObject.name = this.name;
  52276. serializationObject.id = this.id;
  52277. // Emitter
  52278. if (this.emitter.position) {
  52279. var emitterMesh = this.emitter;
  52280. serializationObject.emitterId = emitterMesh.id;
  52281. }
  52282. else {
  52283. var emitterPosition = this.emitter;
  52284. serializationObject.emitter = emitterPosition.asArray();
  52285. }
  52286. serializationObject.capacity = this.getCapacity();
  52287. if (this.particleTexture) {
  52288. serializationObject.textureName = this.particleTexture.name;
  52289. }
  52290. // Animations
  52291. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52292. // Particle system
  52293. serializationObject.minAngularSpeed = this.minAngularSpeed;
  52294. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  52295. serializationObject.minSize = this.minSize;
  52296. serializationObject.maxSize = this.maxSize;
  52297. serializationObject.minEmitPower = this.minEmitPower;
  52298. serializationObject.maxEmitPower = this.maxEmitPower;
  52299. serializationObject.minLifeTime = this.minLifeTime;
  52300. serializationObject.maxLifeTime = this.maxLifeTime;
  52301. serializationObject.emitRate = this.emitRate;
  52302. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52303. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52304. serializationObject.gravity = this.gravity.asArray();
  52305. serializationObject.direction1 = this.direction1.asArray();
  52306. serializationObject.direction2 = this.direction2.asArray();
  52307. serializationObject.color1 = this.color1.asArray();
  52308. serializationObject.color2 = this.color2.asArray();
  52309. serializationObject.colorDead = this.colorDead.asArray();
  52310. serializationObject.updateSpeed = this.updateSpeed;
  52311. serializationObject.targetStopDuration = this.targetStopDuration;
  52312. serializationObject.textureMask = this.textureMask.asArray();
  52313. serializationObject.blendMode = this.blendMode;
  52314. serializationObject.customShader = this.customShader;
  52315. serializationObject.preventAutoStart = this.preventAutoStart;
  52316. serializationObject.startSpriteCellID = this.startSpriteCellID;
  52317. serializationObject.endSpriteCellID = this.endSpriteCellID;
  52318. serializationObject.spriteCellLoop = this.spriteCellLoop;
  52319. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  52320. serializationObject.spriteCellWidth = this.spriteCellWidth;
  52321. serializationObject.spriteCellHeight = this.spriteCellHeight;
  52322. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  52323. // Emitter
  52324. if (this.particleEmitterType) {
  52325. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52326. }
  52327. return serializationObject;
  52328. };
  52329. /**
  52330. * Parses a JSON object to create a particle system.
  52331. * @param parsedParticleSystem The JSON object to parse
  52332. * @param scene The scene to create the particle system in
  52333. * @param rootUrl The root url to use to load external dependencies like texture
  52334. * @returns the Parsed particle system
  52335. */
  52336. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52337. var name = parsedParticleSystem.name;
  52338. var custom = null;
  52339. var program = null;
  52340. if (parsedParticleSystem.customShader) {
  52341. program = parsedParticleSystem.customShader;
  52342. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52343. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52344. }
  52345. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  52346. particleSystem.customShader = program;
  52347. if (parsedParticleSystem.id) {
  52348. particleSystem.id = parsedParticleSystem.id;
  52349. }
  52350. // Auto start
  52351. if (parsedParticleSystem.preventAutoStart) {
  52352. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  52353. }
  52354. // Texture
  52355. if (parsedParticleSystem.textureName) {
  52356. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52357. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52358. }
  52359. // Emitter
  52360. if (parsedParticleSystem.emitterId) {
  52361. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52362. }
  52363. else {
  52364. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52365. }
  52366. // Animations
  52367. if (parsedParticleSystem.animations) {
  52368. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52369. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52370. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52371. }
  52372. }
  52373. if (parsedParticleSystem.autoAnimate) {
  52374. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  52375. }
  52376. // Particle system
  52377. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  52378. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  52379. particleSystem.minSize = parsedParticleSystem.minSize;
  52380. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52381. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52382. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52383. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52384. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52385. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52386. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  52387. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  52388. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52389. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  52390. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  52391. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52392. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52393. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52394. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52395. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52396. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  52397. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52398. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  52399. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  52400. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  52401. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  52402. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  52403. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  52404. if (!particleSystem.preventAutoStart) {
  52405. particleSystem.start();
  52406. }
  52407. return particleSystem;
  52408. };
  52409. /**
  52410. * Source color is added to the destination color without alpha affecting the result.
  52411. */
  52412. ParticleSystem.BLENDMODE_ONEONE = 0;
  52413. /**
  52414. * Blend current color and particle color using particle’s alpha.
  52415. */
  52416. ParticleSystem.BLENDMODE_STANDARD = 1;
  52417. return ParticleSystem;
  52418. }());
  52419. BABYLON.ParticleSystem = ParticleSystem;
  52420. })(BABYLON || (BABYLON = {}));
  52421. //# sourceMappingURL=babylon.particleSystem.js.map
  52422. "use strict";
  52423. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  52424. "use strict";
  52425. var BABYLON;
  52426. (function (BABYLON) {
  52427. /**
  52428. * Particle emitter emitting particles from the inside of a box.
  52429. * It emits the particles randomly between 2 given directions.
  52430. */
  52431. var BoxParticleEmitter = /** @class */ (function () {
  52432. /**
  52433. * Creates a new instance of @see BoxParticleEmitter
  52434. */
  52435. function BoxParticleEmitter() {
  52436. /**
  52437. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52438. */
  52439. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  52440. /**
  52441. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52442. */
  52443. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  52444. /**
  52445. * 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.
  52446. */
  52447. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  52448. /**
  52449. * 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.
  52450. */
  52451. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  52452. }
  52453. /**
  52454. * Called by the particle System when the direction is computed for the created particle.
  52455. * @param emitPower is the power of the particle (speed)
  52456. * @param worldMatrix is the world matrix of the particle system
  52457. * @param directionToUpdate is the direction vector to update with the result
  52458. * @param particle is the particle we are computed the direction for
  52459. */
  52460. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52461. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52462. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52463. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52464. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52465. };
  52466. /**
  52467. * Called by the particle System when the position is computed for the created particle.
  52468. * @param worldMatrix is the world matrix of the particle system
  52469. * @param positionToUpdate is the position vector to update with the result
  52470. * @param particle is the particle we are computed the position for
  52471. */
  52472. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52473. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  52474. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  52475. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  52476. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52477. };
  52478. /**
  52479. * Clones the current emitter and returns a copy of it
  52480. * @returns the new emitter
  52481. */
  52482. BoxParticleEmitter.prototype.clone = function () {
  52483. var newOne = new BoxParticleEmitter();
  52484. BABYLON.Tools.DeepCopy(this, newOne);
  52485. return newOne;
  52486. };
  52487. /**
  52488. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52489. * @param effect defines the update shader
  52490. */
  52491. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  52492. effect.setVector3("direction1", this.direction1);
  52493. effect.setVector3("direction2", this.direction2);
  52494. effect.setVector3("minEmitBox", this.minEmitBox);
  52495. effect.setVector3("maxEmitBox", this.maxEmitBox);
  52496. };
  52497. /**
  52498. * Returns a string to use to update the GPU particles update shader
  52499. * @returns a string containng the defines string
  52500. */
  52501. BoxParticleEmitter.prototype.getEffectDefines = function () {
  52502. return "#define BOXEMITTER";
  52503. };
  52504. /**
  52505. * Returns the string "BoxEmitter"
  52506. * @returns a string containing the class name
  52507. */
  52508. BoxParticleEmitter.prototype.getClassName = function () {
  52509. return "BoxEmitter";
  52510. };
  52511. /**
  52512. * Serializes the particle system to a JSON object.
  52513. * @returns the JSON object
  52514. */
  52515. BoxParticleEmitter.prototype.serialize = function () {
  52516. var serializationObject = {};
  52517. serializationObject.type = this.getClassName();
  52518. serializationObject.direction1 = this.direction1.asArray();
  52519. ;
  52520. serializationObject.direction2 = this.direction2.asArray();
  52521. ;
  52522. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52523. ;
  52524. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52525. ;
  52526. return serializationObject;
  52527. };
  52528. /**
  52529. * Parse properties from a JSON object
  52530. * @param serializationObject defines the JSON object
  52531. */
  52532. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  52533. this.direction1.copyFrom(serializationObject.direction1);
  52534. this.direction2.copyFrom(serializationObject.direction2);
  52535. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  52536. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  52537. };
  52538. return BoxParticleEmitter;
  52539. }());
  52540. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  52541. })(BABYLON || (BABYLON = {}));
  52542. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  52543. "use strict";
  52544. var BABYLON;
  52545. (function (BABYLON) {
  52546. /**
  52547. * Particle emitter emitting particles from the inside of a cone.
  52548. * It emits the particles alongside the cone volume from the base to the particle.
  52549. * The emission direction might be randomized.
  52550. */
  52551. var ConeParticleEmitter = /** @class */ (function () {
  52552. /**
  52553. * Creates a new instance of @see ConeParticleEmitter
  52554. * @param radius the radius of the emission cone (1 by default)
  52555. * @param angles the cone base angle (PI by default)
  52556. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52557. */
  52558. function ConeParticleEmitter(radius,
  52559. /**
  52560. * The radius of the emission cone.
  52561. */
  52562. angle,
  52563. /**
  52564. * The cone base angle.
  52565. */
  52566. directionRandomizer) {
  52567. if (radius === void 0) { radius = 1; }
  52568. if (angle === void 0) { angle = Math.PI; }
  52569. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52570. this.angle = angle;
  52571. this.directionRandomizer = directionRandomizer;
  52572. this.radius = radius;
  52573. }
  52574. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  52575. /**
  52576. * Gets the radius of the emission cone.
  52577. */
  52578. get: function () {
  52579. return this._radius;
  52580. },
  52581. /**
  52582. * Sets the radius of the emission cone.
  52583. */
  52584. set: function (value) {
  52585. this._radius = value;
  52586. if (this.angle !== 0) {
  52587. this._height = value / Math.tan(this.angle / 2);
  52588. }
  52589. else {
  52590. this._height = 1;
  52591. }
  52592. },
  52593. enumerable: true,
  52594. configurable: true
  52595. });
  52596. /**
  52597. * Called by the particle System when the direction is computed for the created particle.
  52598. * @param emitPower is the power of the particle (speed)
  52599. * @param worldMatrix is the world matrix of the particle system
  52600. * @param directionToUpdate is the direction vector to update with the result
  52601. * @param particle is the particle we are computed the direction for
  52602. */
  52603. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52604. if (this.angle === 0) {
  52605. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  52606. }
  52607. else {
  52608. // measure the direction Vector from the emitter to the particle.
  52609. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52610. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52611. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52612. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52613. direction.x += randX;
  52614. direction.y += randY;
  52615. direction.z += randZ;
  52616. direction.normalize();
  52617. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52618. }
  52619. };
  52620. /**
  52621. * Called by the particle System when the position is computed for the created particle.
  52622. * @param worldMatrix is the world matrix of the particle system
  52623. * @param positionToUpdate is the position vector to update with the result
  52624. * @param particle is the particle we are computed the position for
  52625. */
  52626. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52627. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  52628. var h = BABYLON.Scalar.RandomRange(0, 1);
  52629. // Better distribution in a cone at normal angles.
  52630. h = 1 - h * h;
  52631. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  52632. radius = radius * h / this._height;
  52633. var randX = radius * Math.sin(s);
  52634. var randZ = radius * Math.cos(s);
  52635. var randY = h * this._height;
  52636. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52637. };
  52638. /**
  52639. * Clones the current emitter and returns a copy of it
  52640. * @returns the new emitter
  52641. */
  52642. ConeParticleEmitter.prototype.clone = function () {
  52643. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  52644. BABYLON.Tools.DeepCopy(this, newOne);
  52645. return newOne;
  52646. };
  52647. /**
  52648. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52649. * @param effect defines the update shader
  52650. */
  52651. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52652. effect.setFloat("radius", this.radius);
  52653. effect.setFloat("angle", this.angle);
  52654. effect.setFloat("height", this._height);
  52655. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52656. };
  52657. /**
  52658. * Returns a string to use to update the GPU particles update shader
  52659. * @returns a string containng the defines string
  52660. */
  52661. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52662. return "#define CONEEMITTER";
  52663. };
  52664. /**
  52665. * Returns the string "BoxEmitter"
  52666. * @returns a string containing the class name
  52667. */
  52668. ConeParticleEmitter.prototype.getClassName = function () {
  52669. return "ConeEmitter";
  52670. };
  52671. /**
  52672. * Serializes the particle system to a JSON object.
  52673. * @returns the JSON object
  52674. */
  52675. ConeParticleEmitter.prototype.serialize = function () {
  52676. var serializationObject = {};
  52677. serializationObject.type = this.getClassName();
  52678. serializationObject.radius = this.radius;
  52679. serializationObject.angle = this.angle;
  52680. serializationObject.directionRandomizer = this.directionRandomizer;
  52681. return serializationObject;
  52682. };
  52683. /**
  52684. * Parse properties from a JSON object
  52685. * @param serializationObject defines the JSON object
  52686. */
  52687. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52688. this.radius = serializationObject.radius;
  52689. this.angle = serializationObject.angle;
  52690. this.directionRandomizer = serializationObject.directionRandomizer;
  52691. };
  52692. return ConeParticleEmitter;
  52693. }());
  52694. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52695. })(BABYLON || (BABYLON = {}));
  52696. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52697. "use strict";
  52698. var BABYLON;
  52699. (function (BABYLON) {
  52700. /**
  52701. * Particle emitter emitting particles from the inside of a sphere.
  52702. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52703. */
  52704. var SphereParticleEmitter = /** @class */ (function () {
  52705. /**
  52706. * Creates a new instance of @see SphereParticleEmitter
  52707. * @param radius the radius of the emission sphere (1 by default)
  52708. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52709. */
  52710. function SphereParticleEmitter(
  52711. /**
  52712. * The radius of the emission sphere.
  52713. */
  52714. radius,
  52715. /**
  52716. * How much to randomize the particle direction [0-1].
  52717. */
  52718. directionRandomizer) {
  52719. if (radius === void 0) { radius = 1; }
  52720. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52721. this.radius = radius;
  52722. this.directionRandomizer = directionRandomizer;
  52723. }
  52724. /**
  52725. * Called by the particle System when the direction is computed for the created particle.
  52726. * @param emitPower is the power of the particle (speed)
  52727. * @param worldMatrix is the world matrix of the particle system
  52728. * @param directionToUpdate is the direction vector to update with the result
  52729. * @param particle is the particle we are computed the direction for
  52730. */
  52731. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52732. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52733. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52734. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52735. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52736. direction.x += randX;
  52737. direction.y += randY;
  52738. direction.z += randZ;
  52739. direction.normalize();
  52740. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52741. };
  52742. /**
  52743. * Called by the particle System when the position is computed for the created particle.
  52744. * @param worldMatrix is the world matrix of the particle system
  52745. * @param positionToUpdate is the position vector to update with the result
  52746. * @param particle is the particle we are computed the position for
  52747. */
  52748. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52749. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52750. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52751. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52752. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52753. var randY = randRadius * Math.cos(theta);
  52754. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52755. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52756. };
  52757. /**
  52758. * Clones the current emitter and returns a copy of it
  52759. * @returns the new emitter
  52760. */
  52761. SphereParticleEmitter.prototype.clone = function () {
  52762. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52763. BABYLON.Tools.DeepCopy(this, newOne);
  52764. return newOne;
  52765. };
  52766. /**
  52767. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52768. * @param effect defines the update shader
  52769. */
  52770. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52771. effect.setFloat("radius", this.radius);
  52772. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52773. };
  52774. /**
  52775. * Returns a string to use to update the GPU particles update shader
  52776. * @returns a string containng the defines string
  52777. */
  52778. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52779. return "#define SPHEREEMITTER";
  52780. };
  52781. /**
  52782. * Returns the string "SphereParticleEmitter"
  52783. * @returns a string containing the class name
  52784. */
  52785. SphereParticleEmitter.prototype.getClassName = function () {
  52786. return "SphereParticleEmitter";
  52787. };
  52788. /**
  52789. * Serializes the particle system to a JSON object.
  52790. * @returns the JSON object
  52791. */
  52792. SphereParticleEmitter.prototype.serialize = function () {
  52793. var serializationObject = {};
  52794. serializationObject.type = this.getClassName();
  52795. serializationObject.radius = this.radius;
  52796. serializationObject.directionRandomizer = this.directionRandomizer;
  52797. return serializationObject;
  52798. };
  52799. /**
  52800. * Parse properties from a JSON object
  52801. * @param serializationObject defines the JSON object
  52802. */
  52803. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52804. this.radius = serializationObject.radius;
  52805. this.directionRandomizer = serializationObject.directionRandomizer;
  52806. };
  52807. return SphereParticleEmitter;
  52808. }());
  52809. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52810. /**
  52811. * Particle emitter emitting particles from the inside of a sphere.
  52812. * It emits the particles randomly between two vectors.
  52813. */
  52814. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52815. __extends(SphereDirectedParticleEmitter, _super);
  52816. /**
  52817. * Creates a new instance of @see SphereDirectedParticleEmitter
  52818. * @param radius the radius of the emission sphere (1 by default)
  52819. * @param direction1 the min limit of the emission direction (up vector by default)
  52820. * @param direction2 the max limit of the emission direction (up vector by default)
  52821. */
  52822. function SphereDirectedParticleEmitter(radius,
  52823. /**
  52824. * The min limit of the emission direction.
  52825. */
  52826. direction1,
  52827. /**
  52828. * The max limit of the emission direction.
  52829. */
  52830. direction2) {
  52831. if (radius === void 0) { radius = 1; }
  52832. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52833. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52834. var _this = _super.call(this, radius) || this;
  52835. _this.direction1 = direction1;
  52836. _this.direction2 = direction2;
  52837. return _this;
  52838. }
  52839. /**
  52840. * Called by the particle System when the direction is computed for the created particle.
  52841. * @param emitPower is the power of the particle (speed)
  52842. * @param worldMatrix is the world matrix of the particle system
  52843. * @param directionToUpdate is the direction vector to update with the result
  52844. * @param particle is the particle we are computed the direction for
  52845. */
  52846. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52847. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52848. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52849. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52850. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52851. };
  52852. /**
  52853. * Clones the current emitter and returns a copy of it
  52854. * @returns the new emitter
  52855. */
  52856. SphereDirectedParticleEmitter.prototype.clone = function () {
  52857. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52858. BABYLON.Tools.DeepCopy(this, newOne);
  52859. return newOne;
  52860. };
  52861. /**
  52862. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52863. * @param effect defines the update shader
  52864. */
  52865. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52866. effect.setFloat("radius", this.radius);
  52867. effect.setVector3("direction1", this.direction1);
  52868. effect.setVector3("direction2", this.direction2);
  52869. };
  52870. /**
  52871. * Returns a string to use to update the GPU particles update shader
  52872. * @returns a string containng the defines string
  52873. */
  52874. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52875. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52876. };
  52877. /**
  52878. * Returns the string "SphereDirectedParticleEmitter"
  52879. * @returns a string containing the class name
  52880. */
  52881. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52882. return "SphereDirectedParticleEmitter";
  52883. };
  52884. /**
  52885. * Serializes the particle system to a JSON object.
  52886. * @returns the JSON object
  52887. */
  52888. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52889. var serializationObject = _super.prototype.serialize.call(this);
  52890. ;
  52891. serializationObject.direction1 = this.direction1.asArray();
  52892. ;
  52893. serializationObject.direction2 = this.direction2.asArray();
  52894. ;
  52895. return serializationObject;
  52896. };
  52897. /**
  52898. * Parse properties from a JSON object
  52899. * @param serializationObject defines the JSON object
  52900. */
  52901. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52902. _super.prototype.parse.call(this, serializationObject);
  52903. this.direction1.copyFrom(serializationObject.direction1);
  52904. this.direction2.copyFrom(serializationObject.direction2);
  52905. };
  52906. return SphereDirectedParticleEmitter;
  52907. }(SphereParticleEmitter));
  52908. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52909. })(BABYLON || (BABYLON = {}));
  52910. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52911. "use strict";
  52912. var __assign = (this && this.__assign) || Object.assign || function(t) {
  52913. for (var s, i = 1, n = arguments.length; i < n; i++) {
  52914. s = arguments[i];
  52915. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  52916. t[p] = s[p];
  52917. }
  52918. return t;
  52919. };
  52920. var BABYLON;
  52921. (function (BABYLON) {
  52922. /**
  52923. * This represents a GPU particle system in Babylon
  52924. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  52925. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  52926. */
  52927. var GPUParticleSystem = /** @class */ (function () {
  52928. /**
  52929. * Instantiates a GPU particle system.
  52930. * 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.
  52931. * @param name The name of the particle system
  52932. * @param capacity The max number of particles alive at the same time
  52933. * @param scene The scene the particle system belongs to
  52934. */
  52935. function GPUParticleSystem(name, options, scene) {
  52936. /**
  52937. * The emitter represents the Mesh or position we are attaching the particle system to.
  52938. */
  52939. this.emitter = null;
  52940. /**
  52941. * The rendering group used by the Particle system to chose when to render.
  52942. */
  52943. this.renderingGroupId = 0;
  52944. /**
  52945. * The layer mask we are rendering the particles through.
  52946. */
  52947. this.layerMask = 0x0FFFFFFF;
  52948. this._targetIndex = 0;
  52949. this._currentRenderId = -1;
  52950. this._started = false;
  52951. this._stopped = false;
  52952. this._timeDelta = 0;
  52953. this._attributesStrideSize = 14;
  52954. this._actualFrame = 0;
  52955. /**
  52956. * List of animations used by the particle system.
  52957. */
  52958. this.animations = [];
  52959. /**
  52960. * An event triggered when the system is disposed.
  52961. */
  52962. this.onDisposeObservable = new BABYLON.Observable();
  52963. /**
  52964. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  52965. */
  52966. this.updateSpeed = 0.01;
  52967. /**
  52968. * The amount of time the particle system is running (depends of the overall update speed).
  52969. */
  52970. this.targetStopDuration = 0;
  52971. /**
  52972. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  52973. */
  52974. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  52975. /**
  52976. * Minimum life time of emitting particles.
  52977. */
  52978. this.minLifeTime = 1;
  52979. /**
  52980. * Maximum life time of emitting particles.
  52981. */
  52982. this.maxLifeTime = 1;
  52983. /**
  52984. * Minimum Size of emitting particles.
  52985. */
  52986. this.minSize = 1;
  52987. /**
  52988. * Maximum Size of emitting particles.
  52989. */
  52990. this.maxSize = 1;
  52991. /**
  52992. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52993. */
  52994. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52995. /**
  52996. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52997. */
  52998. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52999. /**
  53000. * Color the particle will have at the end of its lifetime.
  53001. */
  53002. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  53003. /**
  53004. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  53005. */
  53006. this.emitRate = 100;
  53007. /**
  53008. * You can use gravity if you want to give an orientation to your particles.
  53009. */
  53010. this.gravity = BABYLON.Vector3.Zero();
  53011. /**
  53012. * Minimum power of emitting particles.
  53013. */
  53014. this.minEmitPower = 1;
  53015. /**
  53016. * Maximum power of emitting particles.
  53017. */
  53018. this.maxEmitPower = 1;
  53019. /**
  53020. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  53021. * to override the particles.
  53022. */
  53023. this.forceDepthWrite = false;
  53024. this.id = name;
  53025. this.name = name;
  53026. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53027. this._engine = this._scene.getEngine();
  53028. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  53029. this._capacity = fullOptions.capacity;
  53030. this._activeCount = fullOptions.capacity;
  53031. this._currentActiveCount = 0;
  53032. this._scene.particleSystems.push(this);
  53033. this._updateEffectOptions = {
  53034. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  53035. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  53036. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  53037. uniformBuffersNames: [],
  53038. samplers: ["randomSampler"],
  53039. defines: "",
  53040. fallbacks: null,
  53041. onCompiled: null,
  53042. onError: null,
  53043. indexParameters: null,
  53044. maxSimultaneousLights: 0,
  53045. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  53046. };
  53047. // Random data
  53048. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  53049. var d = [];
  53050. for (var i = 0; i < maxTextureSize; ++i) {
  53051. d.push(Math.random());
  53052. d.push(Math.random());
  53053. d.push(Math.random());
  53054. d.push(Math.random());
  53055. }
  53056. 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);
  53057. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53058. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53059. this._randomTextureSize = maxTextureSize;
  53060. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  53061. }
  53062. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  53063. /**
  53064. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  53065. */
  53066. get: function () {
  53067. if (!BABYLON.Engine.LastCreatedEngine) {
  53068. return false;
  53069. }
  53070. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  53071. },
  53072. enumerable: true,
  53073. configurable: true
  53074. });
  53075. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  53076. /**
  53077. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53078. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53079. */
  53080. get: function () {
  53081. if (this.particleEmitterType.direction1) {
  53082. return this.particleEmitterType.direction1;
  53083. }
  53084. return BABYLON.Vector3.Zero();
  53085. },
  53086. set: function (value) {
  53087. if (this.particleEmitterType.direction1) {
  53088. this.particleEmitterType.direction1 = value;
  53089. }
  53090. },
  53091. enumerable: true,
  53092. configurable: true
  53093. });
  53094. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  53095. /**
  53096. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53097. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53098. */
  53099. get: function () {
  53100. if (this.particleEmitterType.direction2) {
  53101. return this.particleEmitterType.direction2;
  53102. }
  53103. return BABYLON.Vector3.Zero();
  53104. },
  53105. set: function (value) {
  53106. if (this.particleEmitterType.direction2) {
  53107. this.particleEmitterType.direction2 = value;
  53108. }
  53109. },
  53110. enumerable: true,
  53111. configurable: true
  53112. });
  53113. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  53114. /**
  53115. * 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.
  53116. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53117. */
  53118. get: function () {
  53119. if (this.particleEmitterType.minEmitBox) {
  53120. return this.particleEmitterType.minEmitBox;
  53121. }
  53122. return BABYLON.Vector3.Zero();
  53123. },
  53124. set: function (value) {
  53125. if (this.particleEmitterType.minEmitBox) {
  53126. this.particleEmitterType.minEmitBox = value;
  53127. }
  53128. },
  53129. enumerable: true,
  53130. configurable: true
  53131. });
  53132. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  53133. /**
  53134. * 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.
  53135. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53136. */
  53137. get: function () {
  53138. if (this.particleEmitterType.maxEmitBox) {
  53139. return this.particleEmitterType.maxEmitBox;
  53140. }
  53141. return BABYLON.Vector3.Zero();
  53142. },
  53143. set: function (value) {
  53144. if (this.particleEmitterType.maxEmitBox) {
  53145. this.particleEmitterType.maxEmitBox = value;
  53146. }
  53147. },
  53148. enumerable: true,
  53149. configurable: true
  53150. });
  53151. /**
  53152. * Gets the maximum number of particles active at the same time.
  53153. * @returns The max number of active particles.
  53154. */
  53155. GPUParticleSystem.prototype.getCapacity = function () {
  53156. return this._capacity;
  53157. };
  53158. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  53159. /**
  53160. * Gets or set the number of active particles
  53161. */
  53162. get: function () {
  53163. return this._activeCount;
  53164. },
  53165. set: function (value) {
  53166. this._activeCount = Math.min(value, this._capacity);
  53167. },
  53168. enumerable: true,
  53169. configurable: true
  53170. });
  53171. /**
  53172. * Is this system ready to be used/rendered
  53173. * @return true if the system is ready
  53174. */
  53175. GPUParticleSystem.prototype.isReady = function () {
  53176. if (!this.emitter || !this._updateEffect || !this._renderEffect ||
  53177. !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  53178. return false;
  53179. }
  53180. return true;
  53181. };
  53182. /**
  53183. * Gets Wether the system has been started.
  53184. * @returns True if it has been started, otherwise false.
  53185. */
  53186. GPUParticleSystem.prototype.isStarted = function () {
  53187. return this._started;
  53188. };
  53189. /**
  53190. * Starts the particle system and begins to emit.
  53191. */
  53192. GPUParticleSystem.prototype.start = function () {
  53193. this._started = true;
  53194. this._stopped = false;
  53195. };
  53196. /**
  53197. * Stops the particle system.
  53198. */
  53199. GPUParticleSystem.prototype.stop = function () {
  53200. this._stopped = true;
  53201. };
  53202. /**
  53203. * Remove all active particles
  53204. */
  53205. GPUParticleSystem.prototype.reset = function () {
  53206. this._releaseBuffers();
  53207. this._releaseVAOs();
  53208. this._currentActiveCount = 0;
  53209. this._targetIndex = 0;
  53210. };
  53211. /**
  53212. * Returns the string "GPUParticleSystem"
  53213. * @returns a string containing the class name
  53214. */
  53215. GPUParticleSystem.prototype.getClassName = function () {
  53216. return "GPUParticleSystem";
  53217. };
  53218. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  53219. var updateVertexBuffers = {};
  53220. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  53221. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  53222. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  53223. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  53224. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  53225. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  53226. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  53227. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  53228. this._engine.bindArrayBuffer(null);
  53229. return vao;
  53230. };
  53231. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  53232. var renderVertexBuffers = {};
  53233. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  53234. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  53235. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  53236. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  53237. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  53238. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  53239. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  53240. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  53241. this._engine.bindArrayBuffer(null);
  53242. return vao;
  53243. };
  53244. GPUParticleSystem.prototype._initialize = function (force) {
  53245. if (force === void 0) { force = false; }
  53246. if (this._buffer0 && !force) {
  53247. return;
  53248. }
  53249. var engine = this._scene.getEngine();
  53250. var data = new Array();
  53251. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  53252. // position
  53253. data.push(0.0);
  53254. data.push(0.0);
  53255. data.push(0.0);
  53256. // Age and life
  53257. data.push(0.0); // create the particle as a dead one to create a new one at start
  53258. data.push(0.0);
  53259. // Seed
  53260. data.push(Math.random());
  53261. // Size
  53262. data.push(0.0);
  53263. // color
  53264. data.push(0.0);
  53265. data.push(0.0);
  53266. data.push(0.0);
  53267. data.push(0.0);
  53268. // direction
  53269. data.push(0.0);
  53270. data.push(0.0);
  53271. data.push(0.0);
  53272. }
  53273. // Sprite data
  53274. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  53275. -0.5, 0.5, 0, 1,
  53276. -0.5, -0.5, 0, 0,
  53277. 0.5, -0.5, 1, 0]);
  53278. // Buffers
  53279. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53280. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53281. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  53282. // Update VAO
  53283. this._updateVAO = [];
  53284. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  53285. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  53286. // Render VAO
  53287. this._renderVAO = [];
  53288. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  53289. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  53290. // Links
  53291. this._sourceBuffer = this._buffer0;
  53292. this._targetBuffer = this._buffer1;
  53293. };
  53294. /** @ignore */
  53295. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  53296. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  53297. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  53298. return;
  53299. }
  53300. this._updateEffectOptions.defines = defines;
  53301. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  53302. };
  53303. /** @ignore */
  53304. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  53305. var defines = "";
  53306. if (this._scene.clipPlane) {
  53307. defines = "\n#define CLIPPLANE";
  53308. }
  53309. if (this._renderEffect && this._renderEffect.defines === defines) {
  53310. return;
  53311. }
  53312. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  53313. };
  53314. /**
  53315. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  53316. */
  53317. GPUParticleSystem.prototype.animate = function () {
  53318. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  53319. this._actualFrame += this._timeDelta;
  53320. if (!this._stopped) {
  53321. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  53322. this.stop();
  53323. }
  53324. }
  53325. };
  53326. /**
  53327. * Renders the particle system in its current state.
  53328. * @returns the current number of particles
  53329. */
  53330. GPUParticleSystem.prototype.render = function () {
  53331. if (!this._started) {
  53332. return 0;
  53333. }
  53334. this._recreateUpdateEffect();
  53335. this._recreateRenderEffect();
  53336. if (!this.isReady()) {
  53337. return 0;
  53338. }
  53339. if (this._currentRenderId === this._scene.getRenderId()) {
  53340. return 0;
  53341. }
  53342. this._currentRenderId = this._scene.getRenderId();
  53343. // Get everything ready to render
  53344. this._initialize();
  53345. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  53346. // Enable update effect
  53347. this._engine.enableEffect(this._updateEffect);
  53348. this._engine.setState(false);
  53349. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  53350. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  53351. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  53352. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  53353. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  53354. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  53355. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  53356. this._updateEffect.setDirectColor4("color1", this.color1);
  53357. this._updateEffect.setDirectColor4("color2", this.color2);
  53358. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  53359. this._updateEffect.setVector3("gravity", this.gravity);
  53360. if (this.particleEmitterType) {
  53361. this.particleEmitterType.applyToShader(this._updateEffect);
  53362. }
  53363. var emitterWM;
  53364. if (this.emitter.position) {
  53365. var emitterMesh = this.emitter;
  53366. emitterWM = emitterMesh.getWorldMatrix();
  53367. }
  53368. else {
  53369. var emitterPosition = this.emitter;
  53370. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  53371. }
  53372. this._updateEffect.setMatrix("emitterWM", emitterWM);
  53373. // Bind source VAO
  53374. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  53375. // Update
  53376. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  53377. this._engine.setRasterizerState(false);
  53378. this._engine.beginTransformFeedback();
  53379. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  53380. this._engine.endTransformFeedback();
  53381. this._engine.setRasterizerState(true);
  53382. this._engine.bindTransformFeedbackBuffer(null);
  53383. // Enable render effect
  53384. this._engine.enableEffect(this._renderEffect);
  53385. var viewMatrix = this._scene.getViewMatrix();
  53386. this._renderEffect.setMatrix("view", viewMatrix);
  53387. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  53388. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  53389. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  53390. if (this._scene.clipPlane) {
  53391. var clipPlane = this._scene.clipPlane;
  53392. var invView = viewMatrix.clone();
  53393. invView.invert();
  53394. this._renderEffect.setMatrix("invView", invView);
  53395. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  53396. }
  53397. // Draw order
  53398. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  53399. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  53400. }
  53401. else {
  53402. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53403. }
  53404. if (this.forceDepthWrite) {
  53405. this._engine.setDepthWrite(true);
  53406. }
  53407. // Bind source VAO
  53408. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  53409. // Render
  53410. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  53411. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53412. // Switch VAOs
  53413. this._targetIndex++;
  53414. if (this._targetIndex === 2) {
  53415. this._targetIndex = 0;
  53416. }
  53417. // Switch buffers
  53418. var tmpBuffer = this._sourceBuffer;
  53419. this._sourceBuffer = this._targetBuffer;
  53420. this._targetBuffer = tmpBuffer;
  53421. return this._currentActiveCount;
  53422. };
  53423. /**
  53424. * Rebuilds the particle system
  53425. */
  53426. GPUParticleSystem.prototype.rebuild = function () {
  53427. this._initialize(true);
  53428. };
  53429. GPUParticleSystem.prototype._releaseBuffers = function () {
  53430. if (this._buffer0) {
  53431. this._buffer0.dispose();
  53432. this._buffer0 = null;
  53433. }
  53434. if (this._buffer1) {
  53435. this._buffer1.dispose();
  53436. this._buffer1 = null;
  53437. }
  53438. if (this._spriteBuffer) {
  53439. this._spriteBuffer.dispose();
  53440. this._spriteBuffer = null;
  53441. }
  53442. };
  53443. GPUParticleSystem.prototype._releaseVAOs = function () {
  53444. if (!this._updateVAO) {
  53445. return;
  53446. }
  53447. for (var index = 0; index < this._updateVAO.length; index++) {
  53448. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  53449. }
  53450. this._updateVAO = [];
  53451. for (var index = 0; index < this._renderVAO.length; index++) {
  53452. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  53453. }
  53454. this._renderVAO = [];
  53455. };
  53456. /**
  53457. * Disposes the particle system and free the associated resources
  53458. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  53459. */
  53460. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  53461. if (disposeTexture === void 0) { disposeTexture = true; }
  53462. var index = this._scene.particleSystems.indexOf(this);
  53463. if (index > -1) {
  53464. this._scene.particleSystems.splice(index, 1);
  53465. }
  53466. this._releaseBuffers();
  53467. this._releaseVAOs();
  53468. if (this._randomTexture) {
  53469. this._randomTexture.dispose();
  53470. this._randomTexture = null;
  53471. }
  53472. if (disposeTexture && this.particleTexture) {
  53473. this.particleTexture.dispose();
  53474. this.particleTexture = null;
  53475. }
  53476. // Callback
  53477. this.onDisposeObservable.notifyObservers(this);
  53478. this.onDisposeObservable.clear();
  53479. };
  53480. /**
  53481. * Clones the particle system.
  53482. * @param name The name of the cloned object
  53483. * @param newEmitter The new emitter to use
  53484. * @returns the cloned particle system
  53485. */
  53486. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  53487. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  53488. BABYLON.Tools.DeepCopy(this, result);
  53489. if (newEmitter === undefined) {
  53490. newEmitter = this.emitter;
  53491. }
  53492. result.emitter = newEmitter;
  53493. if (this.particleTexture) {
  53494. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  53495. }
  53496. return result;
  53497. };
  53498. /**
  53499. * Serializes the particle system to a JSON object.
  53500. * @returns the JSON object
  53501. */
  53502. GPUParticleSystem.prototype.serialize = function () {
  53503. var serializationObject = {};
  53504. serializationObject.name = this.name;
  53505. serializationObject.id = this.id;
  53506. // Emitter
  53507. if (this.emitter.position) {
  53508. var emitterMesh = this.emitter;
  53509. serializationObject.emitterId = emitterMesh.id;
  53510. }
  53511. else {
  53512. var emitterPosition = this.emitter;
  53513. serializationObject.emitter = emitterPosition.asArray();
  53514. }
  53515. serializationObject.capacity = this.getCapacity();
  53516. if (this.particleTexture) {
  53517. serializationObject.textureName = this.particleTexture.name;
  53518. }
  53519. // Animations
  53520. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  53521. // Particle system
  53522. serializationObject.activeParticleCount = this.activeParticleCount;
  53523. serializationObject.randomTextureSize = this._randomTextureSize;
  53524. serializationObject.minSize = this.minSize;
  53525. serializationObject.maxSize = this.maxSize;
  53526. serializationObject.minEmitPower = this.minEmitPower;
  53527. serializationObject.maxEmitPower = this.maxEmitPower;
  53528. serializationObject.minLifeTime = this.minLifeTime;
  53529. serializationObject.maxLifeTime = this.maxLifeTime;
  53530. serializationObject.emitRate = this.emitRate;
  53531. serializationObject.gravity = this.gravity.asArray();
  53532. serializationObject.color1 = this.color1.asArray();
  53533. serializationObject.color2 = this.color2.asArray();
  53534. serializationObject.colorDead = this.colorDead.asArray();
  53535. serializationObject.updateSpeed = this.updateSpeed;
  53536. serializationObject.targetStopDuration = this.targetStopDuration;
  53537. serializationObject.blendMode = this.blendMode;
  53538. // Emitter
  53539. if (this.particleEmitterType) {
  53540. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  53541. }
  53542. return serializationObject;
  53543. };
  53544. /**
  53545. * Parses a JSON object to create a GPU particle system.
  53546. * @param parsedParticleSystem The JSON object to parse
  53547. * @param scene The scene to create the particle system in
  53548. * @param rootUrl The root url to use to load external dependencies like texture
  53549. * @returns the parsed GPU particle system
  53550. */
  53551. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  53552. var name = parsedParticleSystem.name;
  53553. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  53554. if (parsedParticleSystem.id) {
  53555. particleSystem.id = parsedParticleSystem.id;
  53556. }
  53557. // Texture
  53558. if (parsedParticleSystem.textureName) {
  53559. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  53560. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  53561. }
  53562. // Emitter
  53563. if (parsedParticleSystem.emitterId) {
  53564. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  53565. }
  53566. else {
  53567. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  53568. }
  53569. // Animations
  53570. if (parsedParticleSystem.animations) {
  53571. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  53572. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  53573. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53574. }
  53575. }
  53576. // Particle system
  53577. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  53578. particleSystem.minSize = parsedParticleSystem.minSize;
  53579. particleSystem.maxSize = parsedParticleSystem.maxSize;
  53580. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  53581. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  53582. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  53583. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  53584. particleSystem.emitRate = parsedParticleSystem.emitRate;
  53585. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  53586. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  53587. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  53588. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  53589. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  53590. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  53591. particleSystem.blendMode = parsedParticleSystem.blendMode;
  53592. // Emitter
  53593. if (parsedParticleSystem.particleEmitterType) {
  53594. var emitterType = void 0;
  53595. switch (parsedParticleSystem.particleEmitterType.type) {
  53596. case "SphereEmitter":
  53597. emitterType = new BABYLON.SphereParticleEmitter();
  53598. break;
  53599. case "SphereDirectedParticleEmitter":
  53600. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  53601. break;
  53602. case "ConeEmitter":
  53603. emitterType = new BABYLON.ConeParticleEmitter();
  53604. break;
  53605. case "BoxEmitter":
  53606. default:
  53607. emitterType = new BABYLON.BoxParticleEmitter();
  53608. break;
  53609. }
  53610. emitterType.parse(parsedParticleSystem.particleEmitterType);
  53611. particleSystem.particleEmitterType = emitterType;
  53612. }
  53613. return particleSystem;
  53614. };
  53615. return GPUParticleSystem;
  53616. }());
  53617. BABYLON.GPUParticleSystem = GPUParticleSystem;
  53618. })(BABYLON || (BABYLON = {}));
  53619. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  53620. "use strict";
  53621. var BABYLON;
  53622. (function (BABYLON) {
  53623. /**
  53624. * Represents one particle of a solid particle system.
  53625. * @see SolidParticleSystem
  53626. */
  53627. var SolidParticle = /** @class */ (function () {
  53628. /**
  53629. * Creates a Solid Particle object.
  53630. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53631. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53632. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53633. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  53634. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  53635. * @param shapeId (integer) is the model shape identifier in the SPS.
  53636. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53637. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  53638. */
  53639. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53640. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  53641. /**
  53642. * particle global index
  53643. */
  53644. this.idx = 0;
  53645. /**
  53646. * The color of the particle
  53647. */
  53648. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53649. /**
  53650. * The world space position of the particle.
  53651. */
  53652. this.position = BABYLON.Vector3.Zero();
  53653. /**
  53654. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  53655. */
  53656. this.rotation = BABYLON.Vector3.Zero();
  53657. /**
  53658. * The scaling of the particle.
  53659. */
  53660. this.scaling = BABYLON.Vector3.One();
  53661. /**
  53662. * The uvs of the particle.
  53663. */
  53664. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  53665. /**
  53666. * The current speed of the particle.
  53667. */
  53668. this.velocity = BABYLON.Vector3.Zero();
  53669. /**
  53670. * The pivot point in the particle local space.
  53671. */
  53672. this.pivot = BABYLON.Vector3.Zero();
  53673. /**
  53674. * Must the particle be translated from its pivot point in its local space ?
  53675. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  53676. * Default : false
  53677. */
  53678. this.translateFromPivot = false;
  53679. /**
  53680. * Is the particle active or not ?
  53681. */
  53682. this.alive = true;
  53683. /**
  53684. * Is the particle visible or not ?
  53685. */
  53686. this.isVisible = true;
  53687. /**
  53688. * Index of this particle in the global "positions" array (Internal use)
  53689. */
  53690. this._pos = 0;
  53691. /**
  53692. * Index of this particle in the global "indices" array (Internal use)
  53693. */
  53694. this._ind = 0;
  53695. /**
  53696. * ModelShape id of this particle
  53697. */
  53698. this.shapeId = 0;
  53699. /**
  53700. * Index of the particle in its shape id (Internal use)
  53701. */
  53702. this.idxInShape = 0;
  53703. /**
  53704. * Still set as invisible in order to skip useless computations (Internal use)
  53705. */
  53706. this._stillInvisible = false;
  53707. /**
  53708. * Last computed particle rotation matrix
  53709. */
  53710. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  53711. /**
  53712. * Parent particle Id, if any.
  53713. * Default null.
  53714. */
  53715. this.parentId = null;
  53716. /**
  53717. * Internal global position in the SPS.
  53718. */
  53719. this._globalPosition = BABYLON.Vector3.Zero();
  53720. this.idx = particleIndex;
  53721. this._pos = positionIndex;
  53722. this._ind = indiceIndex;
  53723. this._model = model;
  53724. this.shapeId = shapeId;
  53725. this.idxInShape = idxInShape;
  53726. this._sps = sps;
  53727. if (modelBoundingInfo) {
  53728. this._modelBoundingInfo = modelBoundingInfo;
  53729. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53730. }
  53731. }
  53732. Object.defineProperty(SolidParticle.prototype, "scale", {
  53733. /**
  53734. * Legacy support, changed scale to scaling
  53735. */
  53736. get: function () {
  53737. return this.scaling;
  53738. },
  53739. /**
  53740. * Legacy support, changed scale to scaling
  53741. */
  53742. set: function (scale) {
  53743. this.scaling = scale;
  53744. },
  53745. enumerable: true,
  53746. configurable: true
  53747. });
  53748. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53749. /**
  53750. * Legacy support, changed quaternion to rotationQuaternion
  53751. */
  53752. get: function () {
  53753. return this.rotationQuaternion;
  53754. },
  53755. /**
  53756. * Legacy support, changed quaternion to rotationQuaternion
  53757. */
  53758. set: function (q) {
  53759. this.rotationQuaternion = q;
  53760. },
  53761. enumerable: true,
  53762. configurable: true
  53763. });
  53764. /**
  53765. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53766. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53767. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  53768. * @returns true if it intersects
  53769. */
  53770. SolidParticle.prototype.intersectsMesh = function (target) {
  53771. if (!this._boundingInfo || !target._boundingInfo) {
  53772. return false;
  53773. }
  53774. if (this._sps._bSphereOnly) {
  53775. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53776. }
  53777. return this._boundingInfo.intersects(target._boundingInfo, false);
  53778. };
  53779. return SolidParticle;
  53780. }());
  53781. BABYLON.SolidParticle = SolidParticle;
  53782. /**
  53783. * Represents the shape of the model used by one particle of a solid particle system.
  53784. * SPS internal tool, don't use it manually.
  53785. * @see SolidParticleSystem
  53786. */
  53787. var ModelShape = /** @class */ (function () {
  53788. /**
  53789. * 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.
  53790. * SPS internal tool, don't use it manually.
  53791. * @ignore
  53792. */
  53793. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  53794. /**
  53795. * length of the shape in the model indices array (internal use)
  53796. */
  53797. this._indicesLength = 0;
  53798. this.shapeID = id;
  53799. this._shape = shape;
  53800. this._indicesLength = indicesLength;
  53801. this._shapeUV = shapeUV;
  53802. this._positionFunction = posFunction;
  53803. this._vertexFunction = vtxFunction;
  53804. }
  53805. return ModelShape;
  53806. }());
  53807. BABYLON.ModelShape = ModelShape;
  53808. /**
  53809. * Represents a Depth Sorted Particle in the solid particle system.
  53810. * @see SolidParticleSystem
  53811. */
  53812. var DepthSortedParticle = /** @class */ (function () {
  53813. function DepthSortedParticle() {
  53814. /**
  53815. * Index of the particle in the "indices" array
  53816. */
  53817. this.ind = 0;
  53818. /**
  53819. * Length of the particle shape in the "indices" array
  53820. */
  53821. this.indicesLength = 0;
  53822. /**
  53823. * Squared distance from the particle to the camera
  53824. */
  53825. this.sqDistance = 0.0;
  53826. }
  53827. return DepthSortedParticle;
  53828. }());
  53829. BABYLON.DepthSortedParticle = DepthSortedParticle;
  53830. })(BABYLON || (BABYLON = {}));
  53831. //# sourceMappingURL=babylon.solidParticle.js.map
  53832. "use strict";
  53833. var BABYLON;
  53834. (function (BABYLON) {
  53835. /**
  53836. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  53837. *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.
  53838. * The SPS is also a particle system. It provides some methods to manage the particles.
  53839. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  53840. *
  53841. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53842. */
  53843. var SolidParticleSystem = /** @class */ (function () {
  53844. /**
  53845. * Creates a SPS (Solid Particle System) object.
  53846. * @param name (String) is the SPS name, this will be the underlying mesh name.
  53847. * @param scene (Scene) is the scene in which the SPS is added.
  53848. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  53849. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  53850. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  53851. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  53852. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53853. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53854. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53855. */
  53856. function SolidParticleSystem(name, scene, options) {
  53857. /**
  53858. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53859. * Example : var p = SPS.particles[i];
  53860. */
  53861. this.particles = new Array();
  53862. /**
  53863. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53864. */
  53865. this.nbParticles = 0;
  53866. /**
  53867. * If the particles must ever face the camera (default false). Useful for planar particles.
  53868. */
  53869. this.billboard = false;
  53870. /**
  53871. * Recompute normals when adding a shape
  53872. */
  53873. this.recomputeNormals = true;
  53874. /**
  53875. * This a counter ofr your own usage. It's not set by any SPS functions.
  53876. */
  53877. this.counter = 0;
  53878. /**
  53879. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53880. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  53881. */
  53882. this.vars = {};
  53883. /**
  53884. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  53885. */
  53886. this._bSphereOnly = false;
  53887. /**
  53888. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  53889. */
  53890. this._bSphereRadiusFactor = 1.0;
  53891. this._positions = new Array();
  53892. this._indices = new Array();
  53893. this._normals = new Array();
  53894. this._colors = new Array();
  53895. this._uvs = new Array();
  53896. this._index = 0; // indices index
  53897. this._updatable = true;
  53898. this._pickable = false;
  53899. this._isVisibilityBoxLocked = false;
  53900. this._alwaysVisible = false;
  53901. this._depthSort = false;
  53902. this._shapeCounter = 0;
  53903. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  53904. this._color = new BABYLON.Color4(0, 0, 0, 0);
  53905. this._computeParticleColor = true;
  53906. this._computeParticleTexture = true;
  53907. this._computeParticleRotation = true;
  53908. this._computeParticleVertex = false;
  53909. this._computeBoundingBox = false;
  53910. this._depthSortParticles = true;
  53911. this._cam_axisZ = BABYLON.Vector3.Zero();
  53912. this._cam_axisY = BABYLON.Vector3.Zero();
  53913. this._cam_axisX = BABYLON.Vector3.Zero();
  53914. this._axisZ = BABYLON.Axis.Z;
  53915. this._camDir = BABYLON.Vector3.Zero();
  53916. this._camInvertedPosition = BABYLON.Vector3.Zero();
  53917. this._rotMatrix = new BABYLON.Matrix();
  53918. this._invertMatrix = new BABYLON.Matrix();
  53919. this._rotated = BABYLON.Vector3.Zero();
  53920. this._quaternion = new BABYLON.Quaternion();
  53921. this._vertex = BABYLON.Vector3.Zero();
  53922. this._normal = BABYLON.Vector3.Zero();
  53923. this._yaw = 0.0;
  53924. this._pitch = 0.0;
  53925. this._roll = 0.0;
  53926. this._halfroll = 0.0;
  53927. this._halfpitch = 0.0;
  53928. this._halfyaw = 0.0;
  53929. this._sinRoll = 0.0;
  53930. this._cosRoll = 0.0;
  53931. this._sinPitch = 0.0;
  53932. this._cosPitch = 0.0;
  53933. this._sinYaw = 0.0;
  53934. this._cosYaw = 0.0;
  53935. this._mustUnrotateFixedNormals = false;
  53936. this._minimum = BABYLON.Vector3.Zero();
  53937. this._maximum = BABYLON.Vector3.Zero();
  53938. this._minBbox = BABYLON.Vector3.Zero();
  53939. this._maxBbox = BABYLON.Vector3.Zero();
  53940. this._particlesIntersect = false;
  53941. this._depthSortFunction = function (p1, p2) {
  53942. return (p2.sqDistance - p1.sqDistance);
  53943. };
  53944. this._needs32Bits = false;
  53945. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  53946. this._scaledPivot = BABYLON.Vector3.Zero();
  53947. this._particleHasParent = false;
  53948. this.name = name;
  53949. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53950. this._camera = scene.activeCamera;
  53951. this._pickable = options ? options.isPickable : false;
  53952. this._depthSort = options ? options.enableDepthSort : false;
  53953. this._particlesIntersect = options ? options.particleIntersection : false;
  53954. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  53955. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  53956. if (options && options.updatable) {
  53957. this._updatable = options.updatable;
  53958. }
  53959. else {
  53960. this._updatable = true;
  53961. }
  53962. if (this._pickable) {
  53963. this.pickedParticles = [];
  53964. }
  53965. if (this._depthSort) {
  53966. this.depthSortedParticles = [];
  53967. }
  53968. }
  53969. /**
  53970. * Builds the SPS underlying mesh. Returns a standard Mesh.
  53971. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  53972. * @returns the created mesh
  53973. */
  53974. SolidParticleSystem.prototype.buildMesh = function () {
  53975. if (this.nbParticles === 0) {
  53976. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  53977. this.addShape(triangle, 1);
  53978. triangle.dispose();
  53979. }
  53980. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  53981. this._positions32 = new Float32Array(this._positions);
  53982. this._uvs32 = new Float32Array(this._uvs);
  53983. this._colors32 = new Float32Array(this._colors);
  53984. if (this.recomputeNormals) {
  53985. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  53986. }
  53987. this._normals32 = new Float32Array(this._normals);
  53988. this._fixedNormal32 = new Float32Array(this._normals);
  53989. if (this._mustUnrotateFixedNormals) {
  53990. this._unrotateFixedNormals();
  53991. }
  53992. var vertexData = new BABYLON.VertexData();
  53993. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  53994. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  53995. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  53996. if (this._uvs32) {
  53997. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  53998. ;
  53999. }
  54000. if (this._colors32) {
  54001. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  54002. }
  54003. var mesh = new BABYLON.Mesh(this.name, this._scene);
  54004. vertexData.applyToMesh(mesh, this._updatable);
  54005. this.mesh = mesh;
  54006. this.mesh.isPickable = this._pickable;
  54007. // free memory
  54008. if (!this._depthSort) {
  54009. this._indices = null;
  54010. }
  54011. this._positions = null;
  54012. this._normals = null;
  54013. this._uvs = null;
  54014. this._colors = null;
  54015. if (!this._updatable) {
  54016. this.particles.length = 0;
  54017. }
  54018. return mesh;
  54019. };
  54020. /**
  54021. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  54022. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  54023. * Thus the particles generated from `digest()` have their property `position` set yet.
  54024. * @param mesh ( Mesh ) is the mesh to be digested
  54025. * @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
  54026. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  54027. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  54028. * @returns the current SPS
  54029. */
  54030. SolidParticleSystem.prototype.digest = function (mesh, options) {
  54031. var size = (options && options.facetNb) || 1;
  54032. var number = (options && options.number) || 0;
  54033. var delta = (options && options.delta) || 0;
  54034. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54035. var meshInd = mesh.getIndices();
  54036. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54037. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54038. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54039. var f = 0; // facet counter
  54040. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  54041. // compute size from number
  54042. if (number) {
  54043. number = (number > totalFacets) ? totalFacets : number;
  54044. size = Math.round(totalFacets / number);
  54045. delta = 0;
  54046. }
  54047. else {
  54048. size = (size > totalFacets) ? totalFacets : size;
  54049. }
  54050. var facetPos = []; // submesh positions
  54051. var facetInd = []; // submesh indices
  54052. var facetUV = []; // submesh UV
  54053. var facetCol = []; // submesh colors
  54054. var barycenter = BABYLON.Vector3.Zero();
  54055. var sizeO = size;
  54056. while (f < totalFacets) {
  54057. size = sizeO + Math.floor((1 + delta) * Math.random());
  54058. if (f > totalFacets - size) {
  54059. size = totalFacets - f;
  54060. }
  54061. // reset temp arrays
  54062. facetPos.length = 0;
  54063. facetInd.length = 0;
  54064. facetUV.length = 0;
  54065. facetCol.length = 0;
  54066. // iterate over "size" facets
  54067. var fi = 0;
  54068. for (var j = f * 3; j < (f + size) * 3; j++) {
  54069. facetInd.push(fi);
  54070. var i = meshInd[j];
  54071. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  54072. if (meshUV) {
  54073. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  54074. }
  54075. if (meshCol) {
  54076. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  54077. }
  54078. fi++;
  54079. }
  54080. // create a model shape for each single particle
  54081. var idx = this.nbParticles;
  54082. var shape = this._posToShape(facetPos);
  54083. var shapeUV = this._uvsToShapeUV(facetUV);
  54084. // compute the barycenter of the shape
  54085. var v;
  54086. for (v = 0; v < shape.length; v++) {
  54087. barycenter.addInPlace(shape[v]);
  54088. }
  54089. barycenter.scaleInPlace(1 / shape.length);
  54090. // shift the shape from its barycenter to the origin
  54091. for (v = 0; v < shape.length; v++) {
  54092. shape[v].subtractInPlace(barycenter);
  54093. }
  54094. var bInfo;
  54095. if (this._particlesIntersect) {
  54096. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  54097. }
  54098. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  54099. // add the particle in the SPS
  54100. var currentPos = this._positions.length;
  54101. var currentInd = this._indices.length;
  54102. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  54103. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  54104. // initialize the particle position
  54105. this.particles[this.nbParticles].position.addInPlace(barycenter);
  54106. this._index += shape.length;
  54107. idx++;
  54108. this.nbParticles++;
  54109. this._shapeCounter++;
  54110. f += size;
  54111. }
  54112. return this;
  54113. };
  54114. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  54115. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  54116. var index = 0;
  54117. var idx = 0;
  54118. for (var p = 0; p < this.particles.length; p++) {
  54119. this._particle = this.particles[p];
  54120. this._shape = this._particle._model._shape;
  54121. if (this._particle.rotationQuaternion) {
  54122. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54123. }
  54124. else {
  54125. this._yaw = this._particle.rotation.y;
  54126. this._pitch = this._particle.rotation.x;
  54127. this._roll = this._particle.rotation.z;
  54128. this._quaternionRotationYPR();
  54129. }
  54130. this._quaternionToRotationMatrix();
  54131. this._rotMatrix.invertToRef(this._invertMatrix);
  54132. for (var pt = 0; pt < this._shape.length; pt++) {
  54133. idx = index + pt * 3;
  54134. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  54135. this._fixedNormal32[idx] = this._normal.x;
  54136. this._fixedNormal32[idx + 1] = this._normal.y;
  54137. this._fixedNormal32[idx + 2] = this._normal.z;
  54138. }
  54139. index = idx + 3;
  54140. }
  54141. };
  54142. //reset copy
  54143. SolidParticleSystem.prototype._resetCopy = function () {
  54144. this._copy.position.x = 0;
  54145. this._copy.position.y = 0;
  54146. this._copy.position.z = 0;
  54147. this._copy.rotation.x = 0;
  54148. this._copy.rotation.y = 0;
  54149. this._copy.rotation.z = 0;
  54150. this._copy.rotationQuaternion = null;
  54151. this._copy.scaling.x = 1.0;
  54152. this._copy.scaling.y = 1.0;
  54153. this._copy.scaling.z = 1.0;
  54154. this._copy.uvs.x = 0;
  54155. this._copy.uvs.y = 0;
  54156. this._copy.uvs.z = 1.0;
  54157. this._copy.uvs.w = 1.0;
  54158. this._copy.color = null;
  54159. this._copy.translateFromPivot = false;
  54160. };
  54161. // _meshBuilder : inserts the shape model in the global SPS mesh
  54162. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  54163. var i;
  54164. var u = 0;
  54165. var c = 0;
  54166. var n = 0;
  54167. this._resetCopy();
  54168. if (options && options.positionFunction) {
  54169. options.positionFunction(this._copy, idx, idxInShape);
  54170. this._mustUnrotateFixedNormals = true;
  54171. }
  54172. if (this._copy.rotationQuaternion) {
  54173. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54174. }
  54175. else {
  54176. this._yaw = this._copy.rotation.y;
  54177. this._pitch = this._copy.rotation.x;
  54178. this._roll = this._copy.rotation.z;
  54179. this._quaternionRotationYPR();
  54180. }
  54181. this._quaternionToRotationMatrix();
  54182. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  54183. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  54184. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  54185. if (this._copy.translateFromPivot) {
  54186. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54187. }
  54188. else {
  54189. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54190. }
  54191. for (i = 0; i < shape.length; i++) {
  54192. this._vertex.x = shape[i].x;
  54193. this._vertex.y = shape[i].y;
  54194. this._vertex.z = shape[i].z;
  54195. if (options && options.vertexFunction) {
  54196. options.vertexFunction(this._copy, this._vertex, i);
  54197. }
  54198. this._vertex.x *= this._copy.scaling.x;
  54199. this._vertex.y *= this._copy.scaling.y;
  54200. this._vertex.z *= this._copy.scaling.z;
  54201. this._vertex.x -= this._scaledPivot.x;
  54202. this._vertex.y -= this._scaledPivot.y;
  54203. this._vertex.z -= this._scaledPivot.z;
  54204. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54205. this._rotated.addInPlace(this._pivotBackTranslation);
  54206. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  54207. if (meshUV) {
  54208. 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);
  54209. u += 2;
  54210. }
  54211. if (this._copy.color) {
  54212. this._color = this._copy.color;
  54213. }
  54214. else if (meshCol && meshCol[c] !== undefined) {
  54215. this._color.r = meshCol[c];
  54216. this._color.g = meshCol[c + 1];
  54217. this._color.b = meshCol[c + 2];
  54218. this._color.a = meshCol[c + 3];
  54219. }
  54220. else {
  54221. this._color.r = 1.0;
  54222. this._color.g = 1.0;
  54223. this._color.b = 1.0;
  54224. this._color.a = 1.0;
  54225. }
  54226. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  54227. c += 4;
  54228. if (!this.recomputeNormals && meshNor) {
  54229. this._normal.x = meshNor[n];
  54230. this._normal.y = meshNor[n + 1];
  54231. this._normal.z = meshNor[n + 2];
  54232. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  54233. normals.push(this._normal.x, this._normal.y, this._normal.z);
  54234. n += 3;
  54235. }
  54236. }
  54237. for (i = 0; i < meshInd.length; i++) {
  54238. var current_ind = p + meshInd[i];
  54239. indices.push(current_ind);
  54240. if (current_ind > 65535) {
  54241. this._needs32Bits = true;
  54242. }
  54243. }
  54244. if (this._pickable) {
  54245. var nbfaces = meshInd.length / 3;
  54246. for (i = 0; i < nbfaces; i++) {
  54247. this.pickedParticles.push({ idx: idx, faceId: i });
  54248. }
  54249. }
  54250. if (this._depthSort) {
  54251. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  54252. }
  54253. return this._copy;
  54254. };
  54255. // returns a shape array from positions array
  54256. SolidParticleSystem.prototype._posToShape = function (positions) {
  54257. var shape = [];
  54258. for (var i = 0; i < positions.length; i += 3) {
  54259. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  54260. }
  54261. return shape;
  54262. };
  54263. // returns a shapeUV array from a Vector4 uvs
  54264. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  54265. var shapeUV = [];
  54266. if (uvs) {
  54267. for (var i = 0; i < uvs.length; i++)
  54268. shapeUV.push(uvs[i]);
  54269. }
  54270. return shapeUV;
  54271. };
  54272. // adds a new particle object in the particles array
  54273. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  54274. if (bInfo === void 0) { bInfo = null; }
  54275. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  54276. this.particles.push(sp);
  54277. return sp;
  54278. };
  54279. /**
  54280. * Adds some particles to the SPS from the model shape. Returns the shape id.
  54281. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  54282. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  54283. * @param nb (positive integer) the number of particles to be created from this model
  54284. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  54285. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  54286. * @returns the number of shapes in the system
  54287. */
  54288. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  54289. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54290. var meshInd = mesh.getIndices();
  54291. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54292. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54293. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54294. var bbInfo;
  54295. if (this._particlesIntersect) {
  54296. bbInfo = mesh.getBoundingInfo();
  54297. }
  54298. var shape = this._posToShape(meshPos);
  54299. var shapeUV = this._uvsToShapeUV(meshUV);
  54300. var posfunc = options ? options.positionFunction : null;
  54301. var vtxfunc = options ? options.vertexFunction : null;
  54302. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  54303. // particles
  54304. var sp;
  54305. var currentCopy;
  54306. var idx = this.nbParticles;
  54307. for (var i = 0; i < nb; i++) {
  54308. var currentPos = this._positions.length;
  54309. var currentInd = this._indices.length;
  54310. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  54311. if (this._updatable) {
  54312. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  54313. sp.position.copyFrom(currentCopy.position);
  54314. sp.rotation.copyFrom(currentCopy.rotation);
  54315. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  54316. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  54317. }
  54318. if (currentCopy.color && sp.color) {
  54319. sp.color.copyFrom(currentCopy.color);
  54320. }
  54321. sp.scaling.copyFrom(currentCopy.scaling);
  54322. sp.uvs.copyFrom(currentCopy.uvs);
  54323. }
  54324. this._index += shape.length;
  54325. idx++;
  54326. }
  54327. this.nbParticles += nb;
  54328. this._shapeCounter++;
  54329. return this._shapeCounter - 1;
  54330. };
  54331. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  54332. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  54333. this._resetCopy();
  54334. if (particle._model._positionFunction) {
  54335. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  54336. }
  54337. if (this._copy.rotationQuaternion) {
  54338. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54339. }
  54340. else {
  54341. this._yaw = this._copy.rotation.y;
  54342. this._pitch = this._copy.rotation.x;
  54343. this._roll = this._copy.rotation.z;
  54344. this._quaternionRotationYPR();
  54345. }
  54346. this._quaternionToRotationMatrix();
  54347. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54348. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54349. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54350. if (this._copy.translateFromPivot) {
  54351. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54352. }
  54353. else {
  54354. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54355. }
  54356. this._shape = particle._model._shape;
  54357. for (var pt = 0; pt < this._shape.length; pt++) {
  54358. this._vertex.x = this._shape[pt].x;
  54359. this._vertex.y = this._shape[pt].y;
  54360. this._vertex.z = this._shape[pt].z;
  54361. if (particle._model._vertexFunction) {
  54362. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  54363. }
  54364. this._vertex.x *= this._copy.scaling.x;
  54365. this._vertex.y *= this._copy.scaling.y;
  54366. this._vertex.z *= this._copy.scaling.z;
  54367. this._vertex.x -= this._scaledPivot.x;
  54368. this._vertex.y -= this._scaledPivot.y;
  54369. this._vertex.z -= this._scaledPivot.z;
  54370. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54371. this._rotated.addInPlace(this._pivotBackTranslation);
  54372. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  54373. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  54374. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  54375. }
  54376. particle.position.x = 0.0;
  54377. particle.position.y = 0.0;
  54378. particle.position.z = 0.0;
  54379. particle.rotation.x = 0.0;
  54380. particle.rotation.y = 0.0;
  54381. particle.rotation.z = 0.0;
  54382. particle.rotationQuaternion = null;
  54383. particle.scaling.x = 1.0;
  54384. particle.scaling.y = 1.0;
  54385. particle.scaling.z = 1.0;
  54386. particle.uvs.x = 0.0;
  54387. particle.uvs.y = 0.0;
  54388. particle.uvs.z = 1.0;
  54389. particle.uvs.w = 1.0;
  54390. particle.pivot.x = 0.0;
  54391. particle.pivot.y = 0.0;
  54392. particle.pivot.z = 0.0;
  54393. particle.translateFromPivot = false;
  54394. particle.parentId = null;
  54395. };
  54396. /**
  54397. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  54398. * @returns the SPS.
  54399. */
  54400. SolidParticleSystem.prototype.rebuildMesh = function () {
  54401. for (var p = 0; p < this.particles.length; p++) {
  54402. this._rebuildParticle(this.particles[p]);
  54403. }
  54404. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54405. return this;
  54406. };
  54407. /**
  54408. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  54409. * This method calls `updateParticle()` for each particle of the SPS.
  54410. * For an animated SPS, it is usually called within the render loop.
  54411. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  54412. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  54413. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  54414. * @returns the SPS.
  54415. */
  54416. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  54417. if (start === void 0) { start = 0; }
  54418. if (end === void 0) { end = this.nbParticles - 1; }
  54419. if (update === void 0) { update = true; }
  54420. if (!this._updatable) {
  54421. return this;
  54422. }
  54423. // custom beforeUpdate
  54424. this.beforeUpdateParticles(start, end, update);
  54425. this._cam_axisX.x = 1.0;
  54426. this._cam_axisX.y = 0.0;
  54427. this._cam_axisX.z = 0.0;
  54428. this._cam_axisY.x = 0.0;
  54429. this._cam_axisY.y = 1.0;
  54430. this._cam_axisY.z = 0.0;
  54431. this._cam_axisZ.x = 0.0;
  54432. this._cam_axisZ.y = 0.0;
  54433. this._cam_axisZ.z = 1.0;
  54434. // cases when the World Matrix is to be computed first
  54435. if (this.billboard || this._depthSort) {
  54436. this.mesh.computeWorldMatrix(true);
  54437. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  54438. }
  54439. // if the particles will always face the camera
  54440. if (this.billboard) {
  54441. // compute the camera position and un-rotate it by the current mesh rotation
  54442. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  54443. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  54444. this._cam_axisZ.normalize();
  54445. // same for camera up vector extracted from the cam view matrix
  54446. var view = this._camera.getViewMatrix(true);
  54447. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  54448. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  54449. this._cam_axisY.normalize();
  54450. this._cam_axisX.normalize();
  54451. }
  54452. // if depthSort, compute the camera global position in the mesh local system
  54453. if (this._depthSort) {
  54454. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  54455. }
  54456. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  54457. var idx = 0; // current position index in the global array positions32
  54458. var index = 0; // position start index in the global array positions32 of the current particle
  54459. var colidx = 0; // current color index in the global array colors32
  54460. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  54461. var uvidx = 0; // current uv index in the global array uvs32
  54462. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  54463. var pt = 0; // current index in the particle model shape
  54464. if (this.mesh.isFacetDataEnabled) {
  54465. this._computeBoundingBox = true;
  54466. }
  54467. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  54468. if (this._computeBoundingBox) {
  54469. if (start == 0 && end == this.nbParticles - 1) {
  54470. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  54471. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  54472. }
  54473. else {
  54474. if (this.mesh._boundingInfo) {
  54475. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  54476. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  54477. }
  54478. }
  54479. }
  54480. // particle loop
  54481. index = this.particles[start]._pos;
  54482. var vpos = (index / 3) | 0;
  54483. colorIndex = vpos * 4;
  54484. uvIndex = vpos * 2;
  54485. for (var p = start; p <= end; p++) {
  54486. this._particle = this.particles[p];
  54487. this._shape = this._particle._model._shape;
  54488. this._shapeUV = this._particle._model._shapeUV;
  54489. // call to custom user function to update the particle properties
  54490. this.updateParticle(this._particle);
  54491. // camera-particle distance for depth sorting
  54492. if (this._depthSort && this._depthSortParticles) {
  54493. var dsp = this.depthSortedParticles[p];
  54494. dsp.ind = this._particle._ind;
  54495. dsp.indicesLength = this._particle._model._indicesLength;
  54496. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  54497. }
  54498. // skip the computations for inactive or already invisible particles
  54499. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  54500. // increment indexes for the next particle
  54501. pt = this._shape.length;
  54502. index += pt * 3;
  54503. colorIndex += pt * 4;
  54504. uvIndex += pt * 2;
  54505. continue;
  54506. }
  54507. if (this._particle.isVisible) {
  54508. this._particle._stillInvisible = false; // un-mark permanent invisibility
  54509. this._particleHasParent = (this._particle.parentId !== null);
  54510. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54511. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54512. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54513. // particle rotation matrix
  54514. if (this.billboard) {
  54515. this._particle.rotation.x = 0.0;
  54516. this._particle.rotation.y = 0.0;
  54517. }
  54518. if (this._computeParticleRotation || this.billboard) {
  54519. if (this._particle.rotationQuaternion) {
  54520. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54521. }
  54522. else {
  54523. this._yaw = this._particle.rotation.y;
  54524. this._pitch = this._particle.rotation.x;
  54525. this._roll = this._particle.rotation.z;
  54526. this._quaternionRotationYPR();
  54527. }
  54528. this._quaternionToRotationMatrix();
  54529. }
  54530. if (this._particleHasParent) {
  54531. this._parent = this.particles[this._particle.parentId];
  54532. 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];
  54533. 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];
  54534. 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];
  54535. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  54536. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  54537. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  54538. if (this._computeParticleRotation || this.billboard) {
  54539. 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];
  54540. 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];
  54541. 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];
  54542. 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];
  54543. 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];
  54544. 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];
  54545. 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];
  54546. 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];
  54547. 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];
  54548. }
  54549. }
  54550. else {
  54551. this._particle._globalPosition.x = this._particle.position.x;
  54552. this._particle._globalPosition.y = this._particle.position.y;
  54553. this._particle._globalPosition.z = this._particle.position.z;
  54554. if (this._computeParticleRotation || this.billboard) {
  54555. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  54556. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  54557. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  54558. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  54559. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  54560. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  54561. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  54562. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  54563. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  54564. }
  54565. }
  54566. if (this._particle.translateFromPivot) {
  54567. this._pivotBackTranslation.x = 0.0;
  54568. this._pivotBackTranslation.y = 0.0;
  54569. this._pivotBackTranslation.z = 0.0;
  54570. }
  54571. else {
  54572. this._pivotBackTranslation.x = this._scaledPivot.x;
  54573. this._pivotBackTranslation.y = this._scaledPivot.y;
  54574. this._pivotBackTranslation.z = this._scaledPivot.z;
  54575. }
  54576. // particle vertex loop
  54577. for (pt = 0; pt < this._shape.length; pt++) {
  54578. idx = index + pt * 3;
  54579. colidx = colorIndex + pt * 4;
  54580. uvidx = uvIndex + pt * 2;
  54581. this._vertex.x = this._shape[pt].x;
  54582. this._vertex.y = this._shape[pt].y;
  54583. this._vertex.z = this._shape[pt].z;
  54584. if (this._computeParticleVertex) {
  54585. this.updateParticleVertex(this._particle, this._vertex, pt);
  54586. }
  54587. // positions
  54588. this._vertex.x *= this._particle.scaling.x;
  54589. this._vertex.y *= this._particle.scaling.y;
  54590. this._vertex.z *= this._particle.scaling.z;
  54591. this._vertex.x -= this._scaledPivot.x;
  54592. this._vertex.y -= this._scaledPivot.y;
  54593. this._vertex.z -= this._scaledPivot.z;
  54594. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54595. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54596. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54597. this._rotated.x += this._pivotBackTranslation.x;
  54598. this._rotated.y += this._pivotBackTranslation.y;
  54599. this._rotated.z += this._pivotBackTranslation.z;
  54600. 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;
  54601. 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;
  54602. 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;
  54603. if (this._computeBoundingBox) {
  54604. if (this._positions32[idx] < this._minimum.x) {
  54605. this._minimum.x = this._positions32[idx];
  54606. }
  54607. if (this._positions32[idx] > this._maximum.x) {
  54608. this._maximum.x = this._positions32[idx];
  54609. }
  54610. if (this._positions32[idx + 1] < this._minimum.y) {
  54611. this._minimum.y = this._positions32[idx + 1];
  54612. }
  54613. if (this._positions32[idx + 1] > this._maximum.y) {
  54614. this._maximum.y = this._positions32[idx + 1];
  54615. }
  54616. if (this._positions32[idx + 2] < this._minimum.z) {
  54617. this._minimum.z = this._positions32[idx + 2];
  54618. }
  54619. if (this._positions32[idx + 2] > this._maximum.z) {
  54620. this._maximum.z = this._positions32[idx + 2];
  54621. }
  54622. }
  54623. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54624. if (!this._computeParticleVertex) {
  54625. this._normal.x = this._fixedNormal32[idx];
  54626. this._normal.y = this._fixedNormal32[idx + 1];
  54627. this._normal.z = this._fixedNormal32[idx + 2];
  54628. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  54629. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  54630. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  54631. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54632. 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;
  54633. 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;
  54634. }
  54635. if (this._computeParticleColor && this._particle.color) {
  54636. this._colors32[colidx] = this._particle.color.r;
  54637. this._colors32[colidx + 1] = this._particle.color.g;
  54638. this._colors32[colidx + 2] = this._particle.color.b;
  54639. this._colors32[colidx + 3] = this._particle.color.a;
  54640. }
  54641. if (this._computeParticleTexture) {
  54642. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54643. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54644. }
  54645. }
  54646. }
  54647. else {
  54648. this._particle._stillInvisible = true; // mark the particle as invisible
  54649. for (pt = 0; pt < this._shape.length; pt++) {
  54650. idx = index + pt * 3;
  54651. colidx = colorIndex + pt * 4;
  54652. uvidx = uvIndex + pt * 2;
  54653. this._positions32[idx] = 0.0;
  54654. this._positions32[idx + 1] = 0.0;
  54655. this._positions32[idx + 2] = 0.0;
  54656. this._normals32[idx] = 0.0;
  54657. this._normals32[idx + 1] = 0.0;
  54658. this._normals32[idx + 2] = 0.0;
  54659. if (this._computeParticleColor && this._particle.color) {
  54660. this._colors32[colidx] = this._particle.color.r;
  54661. this._colors32[colidx + 1] = this._particle.color.g;
  54662. this._colors32[colidx + 2] = this._particle.color.b;
  54663. this._colors32[colidx + 3] = this._particle.color.a;
  54664. }
  54665. if (this._computeParticleTexture) {
  54666. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54667. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54668. }
  54669. }
  54670. }
  54671. // if the particle intersections must be computed : update the bbInfo
  54672. if (this._particlesIntersect) {
  54673. var bInfo = this._particle._boundingInfo;
  54674. var bBox = bInfo.boundingBox;
  54675. var bSphere = bInfo.boundingSphere;
  54676. if (!this._bSphereOnly) {
  54677. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54678. for (var b = 0; b < bBox.vectors.length; b++) {
  54679. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54680. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54681. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54682. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54683. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54684. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54685. 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;
  54686. 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;
  54687. 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;
  54688. }
  54689. bBox._update(this.mesh._worldMatrix);
  54690. }
  54691. // place and scale the particle bouding sphere in the SPS local system, then update it
  54692. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54693. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54694. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54695. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54696. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54697. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54698. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54699. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54700. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54701. 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));
  54702. bSphere._update(this.mesh._worldMatrix);
  54703. }
  54704. // increment indexes for the next particle
  54705. index = idx + 3;
  54706. colorIndex = colidx + 4;
  54707. uvIndex = uvidx + 2;
  54708. }
  54709. // if the VBO must be updated
  54710. if (update) {
  54711. if (this._computeParticleColor) {
  54712. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54713. }
  54714. if (this._computeParticleTexture) {
  54715. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54716. }
  54717. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54718. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54719. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54720. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54721. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54722. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  54723. for (var i = 0; i < this._normals32.length; i++) {
  54724. this._fixedNormal32[i] = this._normals32[i];
  54725. }
  54726. }
  54727. if (!this.mesh.areNormalsFrozen) {
  54728. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54729. }
  54730. }
  54731. if (this._depthSort && this._depthSortParticles) {
  54732. this.depthSortedParticles.sort(this._depthSortFunction);
  54733. var dspl = this.depthSortedParticles.length;
  54734. var sorted = 0;
  54735. var lind = 0;
  54736. var sind = 0;
  54737. var sid = 0;
  54738. for (sorted = 0; sorted < dspl; sorted++) {
  54739. lind = this.depthSortedParticles[sorted].indicesLength;
  54740. sind = this.depthSortedParticles[sorted].ind;
  54741. for (var i = 0; i < lind; i++) {
  54742. this._indices32[sid] = this._indices[sind + i];
  54743. sid++;
  54744. }
  54745. }
  54746. this.mesh.updateIndices(this._indices32);
  54747. }
  54748. }
  54749. if (this._computeBoundingBox) {
  54750. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54751. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54752. }
  54753. this.afterUpdateParticles(start, end, update);
  54754. return this;
  54755. };
  54756. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54757. this._halfroll = this._roll * 0.5;
  54758. this._halfpitch = this._pitch * 0.5;
  54759. this._halfyaw = this._yaw * 0.5;
  54760. this._sinRoll = Math.sin(this._halfroll);
  54761. this._cosRoll = Math.cos(this._halfroll);
  54762. this._sinPitch = Math.sin(this._halfpitch);
  54763. this._cosPitch = Math.cos(this._halfpitch);
  54764. this._sinYaw = Math.sin(this._halfyaw);
  54765. this._cosYaw = Math.cos(this._halfyaw);
  54766. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  54767. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  54768. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  54769. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  54770. };
  54771. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54772. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54773. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54774. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54775. this._rotMatrix.m[3] = 0;
  54776. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54777. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54778. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54779. this._rotMatrix.m[7] = 0;
  54780. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54781. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54782. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54783. this._rotMatrix.m[11] = 0;
  54784. this._rotMatrix.m[12] = 0;
  54785. this._rotMatrix.m[13] = 0;
  54786. this._rotMatrix.m[14] = 0;
  54787. this._rotMatrix.m[15] = 1.0;
  54788. };
  54789. /**
  54790. * Disposes the SPS.
  54791. */
  54792. SolidParticleSystem.prototype.dispose = function () {
  54793. this.mesh.dispose();
  54794. this.vars = null;
  54795. // drop references to internal big arrays for the GC
  54796. this._positions = null;
  54797. this._indices = null;
  54798. this._normals = null;
  54799. this._uvs = null;
  54800. this._colors = null;
  54801. this._indices32 = null;
  54802. this._positions32 = null;
  54803. this._normals32 = null;
  54804. this._fixedNormal32 = null;
  54805. this._uvs32 = null;
  54806. this._colors32 = null;
  54807. this.pickedParticles = null;
  54808. };
  54809. /**
  54810. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54811. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54812. * @returns the SPS.
  54813. */
  54814. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54815. if (!this._isVisibilityBoxLocked) {
  54816. this.mesh.refreshBoundingInfo();
  54817. }
  54818. return this;
  54819. };
  54820. /**
  54821. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54822. * @param size the size (float) of the visibility box
  54823. * note : this doesn't lock the SPS mesh bounding box.
  54824. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54825. */
  54826. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54827. var vis = size / 2;
  54828. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54829. };
  54830. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54831. /**
  54832. * Gets whether the SPS as always visible or not
  54833. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54834. */
  54835. get: function () {
  54836. return this._alwaysVisible;
  54837. },
  54838. /**
  54839. * Sets the SPS as always visible or not
  54840. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54841. */
  54842. set: function (val) {
  54843. this._alwaysVisible = val;
  54844. this.mesh.alwaysSelectAsActiveMesh = val;
  54845. },
  54846. enumerable: true,
  54847. configurable: true
  54848. });
  54849. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54850. /**
  54851. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54852. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54853. */
  54854. get: function () {
  54855. return this._isVisibilityBoxLocked;
  54856. },
  54857. /**
  54858. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54859. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54860. */
  54861. set: function (val) {
  54862. this._isVisibilityBoxLocked = val;
  54863. var boundingInfo = this.mesh.getBoundingInfo();
  54864. boundingInfo.isLocked = val;
  54865. },
  54866. enumerable: true,
  54867. configurable: true
  54868. });
  54869. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54870. /**
  54871. * Gets if `setParticles()` computes the particle rotations or not.
  54872. * Default value : true. The SPS is faster when it's set to false.
  54873. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54874. */
  54875. get: function () {
  54876. return this._computeParticleRotation;
  54877. },
  54878. /**
  54879. * Tells to `setParticles()` to compute the particle rotations or not.
  54880. * Default value : true. The SPS is faster when it's set to false.
  54881. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54882. */
  54883. set: function (val) {
  54884. this._computeParticleRotation = val;
  54885. },
  54886. enumerable: true,
  54887. configurable: true
  54888. });
  54889. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54890. /**
  54891. * Gets if `setParticles()` computes the particle colors or not.
  54892. * Default value : true. The SPS is faster when it's set to false.
  54893. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54894. */
  54895. get: function () {
  54896. return this._computeParticleColor;
  54897. },
  54898. /**
  54899. * Tells to `setParticles()` to compute the particle colors or not.
  54900. * Default value : true. The SPS is faster when it's set to false.
  54901. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54902. */
  54903. set: function (val) {
  54904. this._computeParticleColor = val;
  54905. },
  54906. enumerable: true,
  54907. configurable: true
  54908. });
  54909. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54910. /**
  54911. * Gets if `setParticles()` computes the particle textures or not.
  54912. * Default value : true. The SPS is faster when it's set to false.
  54913. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54914. */
  54915. get: function () {
  54916. return this._computeParticleTexture;
  54917. },
  54918. set: function (val) {
  54919. this._computeParticleTexture = val;
  54920. },
  54921. enumerable: true,
  54922. configurable: true
  54923. });
  54924. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54925. /**
  54926. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  54927. * Default value : false. The SPS is faster when it's set to false.
  54928. * Note : the particle custom vertex positions aren't stored values.
  54929. */
  54930. get: function () {
  54931. return this._computeParticleVertex;
  54932. },
  54933. /**
  54934. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54935. * Default value : false. The SPS is faster when it's set to false.
  54936. * Note : the particle custom vertex positions aren't stored values.
  54937. */
  54938. set: function (val) {
  54939. this._computeParticleVertex = val;
  54940. },
  54941. enumerable: true,
  54942. configurable: true
  54943. });
  54944. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54945. /**
  54946. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  54947. */
  54948. get: function () {
  54949. return this._computeBoundingBox;
  54950. },
  54951. /**
  54952. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54953. */
  54954. set: function (val) {
  54955. this._computeBoundingBox = val;
  54956. },
  54957. enumerable: true,
  54958. configurable: true
  54959. });
  54960. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  54961. /**
  54962. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  54963. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54964. * Default : `true`
  54965. */
  54966. get: function () {
  54967. return this._depthSortParticles;
  54968. },
  54969. /**
  54970. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  54971. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54972. * Default : `true`
  54973. */
  54974. set: function (val) {
  54975. this._depthSortParticles = val;
  54976. },
  54977. enumerable: true,
  54978. configurable: true
  54979. });
  54980. // =======================================================================
  54981. // Particle behavior logic
  54982. // these following methods may be overwritten by the user to fit his needs
  54983. /**
  54984. * This function does nothing. It may be overwritten to set all the particle first values.
  54985. * The SPS doesn't call this function, you may have to call it by your own.
  54986. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54987. */
  54988. SolidParticleSystem.prototype.initParticles = function () {
  54989. };
  54990. /**
  54991. * This function does nothing. It may be overwritten to recycle a particle.
  54992. * The SPS doesn't call this function, you may have to call it by your own.
  54993. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54994. * @param particle The particle to recycle
  54995. * @returns the recycled particle
  54996. */
  54997. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  54998. return particle;
  54999. };
  55000. /**
  55001. * Updates a particle : this function should be overwritten by the user.
  55002. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  55003. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55004. * @example : just set a particle position or velocity and recycle conditions
  55005. * @param particle The particle to update
  55006. * @returns the updated particle
  55007. */
  55008. SolidParticleSystem.prototype.updateParticle = function (particle) {
  55009. return particle;
  55010. };
  55011. /**
  55012. * Updates a vertex of a particle : it can be overwritten by the user.
  55013. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  55014. * @param particle the current particle
  55015. * @param vertex the current index of the current particle
  55016. * @param pt the index of the current vertex in the particle shape
  55017. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  55018. * @example : just set a vertex particle position
  55019. * @returns the updated vertex
  55020. */
  55021. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  55022. return vertex;
  55023. };
  55024. /**
  55025. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  55026. * This does nothing and may be overwritten by the user.
  55027. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55028. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55029. * @param update the boolean update value actually passed to setParticles()
  55030. */
  55031. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  55032. };
  55033. /**
  55034. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  55035. * This will be passed three parameters.
  55036. * This does nothing and may be overwritten by the user.
  55037. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55038. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55039. * @param update the boolean update value actually passed to setParticles()
  55040. */
  55041. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  55042. };
  55043. return SolidParticleSystem;
  55044. }());
  55045. BABYLON.SolidParticleSystem = SolidParticleSystem;
  55046. })(BABYLON || (BABYLON = {}));
  55047. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  55048. "use strict";
  55049. var BABYLON;
  55050. (function (BABYLON) {
  55051. var ShaderMaterial = /** @class */ (function (_super) {
  55052. __extends(ShaderMaterial, _super);
  55053. function ShaderMaterial(name, scene, shaderPath, options) {
  55054. var _this = _super.call(this, name, scene) || this;
  55055. _this._textures = {};
  55056. _this._textureArrays = {};
  55057. _this._floats = {};
  55058. _this._ints = {};
  55059. _this._floatsArrays = {};
  55060. _this._colors3 = {};
  55061. _this._colors3Arrays = {};
  55062. _this._colors4 = {};
  55063. _this._vectors2 = {};
  55064. _this._vectors3 = {};
  55065. _this._vectors4 = {};
  55066. _this._matrices = {};
  55067. _this._matrices3x3 = {};
  55068. _this._matrices2x2 = {};
  55069. _this._vectors2Arrays = {};
  55070. _this._vectors3Arrays = {};
  55071. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  55072. _this._shaderPath = shaderPath;
  55073. options.needAlphaBlending = options.needAlphaBlending || false;
  55074. options.needAlphaTesting = options.needAlphaTesting || false;
  55075. options.attributes = options.attributes || ["position", "normal", "uv"];
  55076. options.uniforms = options.uniforms || ["worldViewProjection"];
  55077. options.uniformBuffers = options.uniformBuffers || [];
  55078. options.samplers = options.samplers || [];
  55079. options.defines = options.defines || [];
  55080. _this._options = options;
  55081. return _this;
  55082. }
  55083. ShaderMaterial.prototype.getClassName = function () {
  55084. return "ShaderMaterial";
  55085. };
  55086. ShaderMaterial.prototype.needAlphaBlending = function () {
  55087. return this._options.needAlphaBlending;
  55088. };
  55089. ShaderMaterial.prototype.needAlphaTesting = function () {
  55090. return this._options.needAlphaTesting;
  55091. };
  55092. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  55093. if (this._options.uniforms.indexOf(uniformName) === -1) {
  55094. this._options.uniforms.push(uniformName);
  55095. }
  55096. };
  55097. ShaderMaterial.prototype.setTexture = function (name, texture) {
  55098. if (this._options.samplers.indexOf(name) === -1) {
  55099. this._options.samplers.push(name);
  55100. }
  55101. this._textures[name] = texture;
  55102. return this;
  55103. };
  55104. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  55105. if (this._options.samplers.indexOf(name) === -1) {
  55106. this._options.samplers.push(name);
  55107. }
  55108. this._checkUniform(name);
  55109. this._textureArrays[name] = textures;
  55110. return this;
  55111. };
  55112. ShaderMaterial.prototype.setFloat = function (name, value) {
  55113. this._checkUniform(name);
  55114. this._floats[name] = value;
  55115. return this;
  55116. };
  55117. ShaderMaterial.prototype.setInt = function (name, value) {
  55118. this._checkUniform(name);
  55119. this._ints[name] = value;
  55120. return this;
  55121. };
  55122. ShaderMaterial.prototype.setFloats = function (name, value) {
  55123. this._checkUniform(name);
  55124. this._floatsArrays[name] = value;
  55125. return this;
  55126. };
  55127. ShaderMaterial.prototype.setColor3 = function (name, value) {
  55128. this._checkUniform(name);
  55129. this._colors3[name] = value;
  55130. return this;
  55131. };
  55132. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  55133. this._checkUniform(name);
  55134. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  55135. color.toArray(arr, arr.length);
  55136. return arr;
  55137. }, []);
  55138. return this;
  55139. };
  55140. ShaderMaterial.prototype.setColor4 = function (name, value) {
  55141. this._checkUniform(name);
  55142. this._colors4[name] = value;
  55143. return this;
  55144. };
  55145. ShaderMaterial.prototype.setVector2 = function (name, value) {
  55146. this._checkUniform(name);
  55147. this._vectors2[name] = value;
  55148. return this;
  55149. };
  55150. ShaderMaterial.prototype.setVector3 = function (name, value) {
  55151. this._checkUniform(name);
  55152. this._vectors3[name] = value;
  55153. return this;
  55154. };
  55155. ShaderMaterial.prototype.setVector4 = function (name, value) {
  55156. this._checkUniform(name);
  55157. this._vectors4[name] = value;
  55158. return this;
  55159. };
  55160. ShaderMaterial.prototype.setMatrix = function (name, value) {
  55161. this._checkUniform(name);
  55162. this._matrices[name] = value;
  55163. return this;
  55164. };
  55165. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  55166. this._checkUniform(name);
  55167. this._matrices3x3[name] = value;
  55168. return this;
  55169. };
  55170. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  55171. this._checkUniform(name);
  55172. this._matrices2x2[name] = value;
  55173. return this;
  55174. };
  55175. ShaderMaterial.prototype.setArray2 = function (name, value) {
  55176. this._checkUniform(name);
  55177. this._vectors2Arrays[name] = value;
  55178. return this;
  55179. };
  55180. ShaderMaterial.prototype.setArray3 = function (name, value) {
  55181. this._checkUniform(name);
  55182. this._vectors3Arrays[name] = value;
  55183. return this;
  55184. };
  55185. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  55186. if (!mesh) {
  55187. return true;
  55188. }
  55189. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  55190. return false;
  55191. }
  55192. return false;
  55193. };
  55194. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  55195. var scene = this.getScene();
  55196. var engine = scene.getEngine();
  55197. if (!this.checkReadyOnEveryCall) {
  55198. if (this._renderId === scene.getRenderId()) {
  55199. if (this._checkCache(scene, mesh, useInstances)) {
  55200. return true;
  55201. }
  55202. }
  55203. }
  55204. // Instances
  55205. var defines = [];
  55206. var attribs = [];
  55207. var fallbacks = new BABYLON.EffectFallbacks();
  55208. if (useInstances) {
  55209. defines.push("#define INSTANCES");
  55210. }
  55211. for (var index = 0; index < this._options.defines.length; index++) {
  55212. defines.push(this._options.defines[index]);
  55213. }
  55214. for (var index = 0; index < this._options.attributes.length; index++) {
  55215. attribs.push(this._options.attributes[index]);
  55216. }
  55217. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  55218. attribs.push(BABYLON.VertexBuffer.ColorKind);
  55219. defines.push("#define VERTEXCOLOR");
  55220. }
  55221. // Bones
  55222. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  55223. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55224. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55225. if (mesh.numBoneInfluencers > 4) {
  55226. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55227. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55228. }
  55229. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55230. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55231. fallbacks.addCPUSkinningFallback(0, mesh);
  55232. if (this._options.uniforms.indexOf("mBones") === -1) {
  55233. this._options.uniforms.push("mBones");
  55234. }
  55235. }
  55236. else {
  55237. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55238. }
  55239. // Textures
  55240. for (var name in this._textures) {
  55241. if (!this._textures[name].isReady()) {
  55242. return false;
  55243. }
  55244. }
  55245. // Alpha test
  55246. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  55247. defines.push("#define ALPHATEST");
  55248. }
  55249. var previousEffect = this._effect;
  55250. var join = defines.join("\n");
  55251. this._effect = engine.createEffect(this._shaderPath, {
  55252. attributes: attribs,
  55253. uniformsNames: this._options.uniforms,
  55254. uniformBuffersNames: this._options.uniformBuffers,
  55255. samplers: this._options.samplers,
  55256. defines: join,
  55257. fallbacks: fallbacks,
  55258. onCompiled: this.onCompiled,
  55259. onError: this.onError
  55260. }, engine);
  55261. if (!this._effect.isReady()) {
  55262. return false;
  55263. }
  55264. if (previousEffect !== this._effect) {
  55265. scene.resetCachedMaterial();
  55266. }
  55267. this._renderId = scene.getRenderId();
  55268. return true;
  55269. };
  55270. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  55271. var scene = this.getScene();
  55272. if (!this._effect) {
  55273. return;
  55274. }
  55275. if (this._options.uniforms.indexOf("world") !== -1) {
  55276. this._effect.setMatrix("world", world);
  55277. }
  55278. if (this._options.uniforms.indexOf("worldView") !== -1) {
  55279. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  55280. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  55281. }
  55282. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  55283. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  55284. }
  55285. };
  55286. ShaderMaterial.prototype.bind = function (world, mesh) {
  55287. // Std values
  55288. this.bindOnlyWorldMatrix(world);
  55289. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  55290. if (this._options.uniforms.indexOf("view") !== -1) {
  55291. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  55292. }
  55293. if (this._options.uniforms.indexOf("projection") !== -1) {
  55294. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  55295. }
  55296. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  55297. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  55298. }
  55299. // Bones
  55300. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  55301. var name;
  55302. // Texture
  55303. for (name in this._textures) {
  55304. this._effect.setTexture(name, this._textures[name]);
  55305. }
  55306. // Texture arrays
  55307. for (name in this._textureArrays) {
  55308. this._effect.setTextureArray(name, this._textureArrays[name]);
  55309. }
  55310. // Int
  55311. for (name in this._ints) {
  55312. this._effect.setInt(name, this._ints[name]);
  55313. }
  55314. // Float
  55315. for (name in this._floats) {
  55316. this._effect.setFloat(name, this._floats[name]);
  55317. }
  55318. // Floats
  55319. for (name in this._floatsArrays) {
  55320. this._effect.setArray(name, this._floatsArrays[name]);
  55321. }
  55322. // Color3
  55323. for (name in this._colors3) {
  55324. this._effect.setColor3(name, this._colors3[name]);
  55325. }
  55326. for (name in this._colors3Arrays) {
  55327. this._effect.setArray3(name, this._colors3Arrays[name]);
  55328. }
  55329. // Color4
  55330. for (name in this._colors4) {
  55331. var color = this._colors4[name];
  55332. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55333. }
  55334. // Vector2
  55335. for (name in this._vectors2) {
  55336. this._effect.setVector2(name, this._vectors2[name]);
  55337. }
  55338. // Vector3
  55339. for (name in this._vectors3) {
  55340. this._effect.setVector3(name, this._vectors3[name]);
  55341. }
  55342. // Vector4
  55343. for (name in this._vectors4) {
  55344. this._effect.setVector4(name, this._vectors4[name]);
  55345. }
  55346. // Matrix
  55347. for (name in this._matrices) {
  55348. this._effect.setMatrix(name, this._matrices[name]);
  55349. }
  55350. // Matrix 3x3
  55351. for (name in this._matrices3x3) {
  55352. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  55353. }
  55354. // Matrix 2x2
  55355. for (name in this._matrices2x2) {
  55356. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  55357. }
  55358. // Vector2Array
  55359. for (name in this._vectors2Arrays) {
  55360. this._effect.setArray2(name, this._vectors2Arrays[name]);
  55361. }
  55362. // Vector3Array
  55363. for (name in this._vectors3Arrays) {
  55364. this._effect.setArray3(name, this._vectors3Arrays[name]);
  55365. }
  55366. }
  55367. this._afterBind(mesh);
  55368. };
  55369. ShaderMaterial.prototype.getActiveTextures = function () {
  55370. var activeTextures = _super.prototype.getActiveTextures.call(this);
  55371. for (var name in this._textures) {
  55372. activeTextures.push(this._textures[name]);
  55373. }
  55374. for (var name in this._textureArrays) {
  55375. var array = this._textureArrays[name];
  55376. for (var index = 0; index < array.length; index++) {
  55377. activeTextures.push(array[index]);
  55378. }
  55379. }
  55380. return activeTextures;
  55381. };
  55382. ShaderMaterial.prototype.hasTexture = function (texture) {
  55383. if (_super.prototype.hasTexture.call(this, texture)) {
  55384. return true;
  55385. }
  55386. for (var name in this._textures) {
  55387. if (this._textures[name] === texture) {
  55388. return true;
  55389. }
  55390. }
  55391. for (var name in this._textureArrays) {
  55392. var array = this._textureArrays[name];
  55393. for (var index = 0; index < array.length; index++) {
  55394. if (array[index] === texture) {
  55395. return true;
  55396. }
  55397. }
  55398. }
  55399. return false;
  55400. };
  55401. ShaderMaterial.prototype.clone = function (name) {
  55402. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  55403. return newShaderMaterial;
  55404. };
  55405. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55406. if (forceDisposeTextures) {
  55407. var name;
  55408. for (name in this._textures) {
  55409. this._textures[name].dispose();
  55410. }
  55411. for (name in this._textureArrays) {
  55412. var array = this._textureArrays[name];
  55413. for (var index = 0; index < array.length; index++) {
  55414. array[index].dispose();
  55415. }
  55416. }
  55417. }
  55418. this._textures = {};
  55419. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55420. };
  55421. ShaderMaterial.prototype.serialize = function () {
  55422. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55423. serializationObject.customType = "BABYLON.ShaderMaterial";
  55424. serializationObject.options = this._options;
  55425. serializationObject.shaderPath = this._shaderPath;
  55426. var name;
  55427. // Texture
  55428. serializationObject.textures = {};
  55429. for (name in this._textures) {
  55430. serializationObject.textures[name] = this._textures[name].serialize();
  55431. }
  55432. // Texture arrays
  55433. serializationObject.textureArrays = {};
  55434. for (name in this._textureArrays) {
  55435. serializationObject.textureArrays[name] = [];
  55436. var array = this._textureArrays[name];
  55437. for (var index = 0; index < array.length; index++) {
  55438. serializationObject.textureArrays[name].push(array[index].serialize());
  55439. }
  55440. }
  55441. // Float
  55442. serializationObject.floats = {};
  55443. for (name in this._floats) {
  55444. serializationObject.floats[name] = this._floats[name];
  55445. }
  55446. // Float s
  55447. serializationObject.FloatArrays = {};
  55448. for (name in this._floatsArrays) {
  55449. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  55450. }
  55451. // Color3
  55452. serializationObject.colors3 = {};
  55453. for (name in this._colors3) {
  55454. serializationObject.colors3[name] = this._colors3[name].asArray();
  55455. }
  55456. // Color3 array
  55457. serializationObject.colors3Arrays = {};
  55458. for (name in this._colors3Arrays) {
  55459. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  55460. }
  55461. // Color4
  55462. serializationObject.colors4 = {};
  55463. for (name in this._colors4) {
  55464. serializationObject.colors4[name] = this._colors4[name].asArray();
  55465. }
  55466. // Vector2
  55467. serializationObject.vectors2 = {};
  55468. for (name in this._vectors2) {
  55469. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  55470. }
  55471. // Vector3
  55472. serializationObject.vectors3 = {};
  55473. for (name in this._vectors3) {
  55474. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  55475. }
  55476. // Vector4
  55477. serializationObject.vectors4 = {};
  55478. for (name in this._vectors4) {
  55479. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  55480. }
  55481. // Matrix
  55482. serializationObject.matrices = {};
  55483. for (name in this._matrices) {
  55484. serializationObject.matrices[name] = this._matrices[name].asArray();
  55485. }
  55486. // Matrix 3x3
  55487. serializationObject.matrices3x3 = {};
  55488. for (name in this._matrices3x3) {
  55489. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  55490. }
  55491. // Matrix 2x2
  55492. serializationObject.matrices2x2 = {};
  55493. for (name in this._matrices2x2) {
  55494. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  55495. }
  55496. // Vector2Array
  55497. serializationObject.vectors2Arrays = {};
  55498. for (name in this._vectors2Arrays) {
  55499. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  55500. }
  55501. // Vector3Array
  55502. serializationObject.vectors3Arrays = {};
  55503. for (name in this._vectors3Arrays) {
  55504. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  55505. }
  55506. return serializationObject;
  55507. };
  55508. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  55509. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  55510. var name;
  55511. // Texture
  55512. for (name in source.textures) {
  55513. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  55514. }
  55515. // Texture arrays
  55516. for (name in source.textureArrays) {
  55517. var array = source.textureArrays[name];
  55518. var textureArray = new Array();
  55519. for (var index = 0; index < array.length; index++) {
  55520. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  55521. }
  55522. material.setTextureArray(name, textureArray);
  55523. }
  55524. // Float
  55525. for (name in source.floats) {
  55526. material.setFloat(name, source.floats[name]);
  55527. }
  55528. // Float s
  55529. for (name in source.floatsArrays) {
  55530. material.setFloats(name, source.floatsArrays[name]);
  55531. }
  55532. // Color3
  55533. for (name in source.colors3) {
  55534. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  55535. }
  55536. // Color3 arrays
  55537. for (name in source.colors3Arrays) {
  55538. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  55539. if (i % 3 === 0) {
  55540. arr.push([num]);
  55541. }
  55542. else {
  55543. arr[arr.length - 1].push(num);
  55544. }
  55545. return arr;
  55546. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  55547. material.setColor3Array(name, colors);
  55548. }
  55549. // Color4
  55550. for (name in source.colors4) {
  55551. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  55552. }
  55553. // Vector2
  55554. for (name in source.vectors2) {
  55555. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  55556. }
  55557. // Vector3
  55558. for (name in source.vectors3) {
  55559. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  55560. }
  55561. // Vector4
  55562. for (name in source.vectors4) {
  55563. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  55564. }
  55565. // Matrix
  55566. for (name in source.matrices) {
  55567. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  55568. }
  55569. // Matrix 3x3
  55570. for (name in source.matrices3x3) {
  55571. material.setMatrix3x3(name, source.matrices3x3[name]);
  55572. }
  55573. // Matrix 2x2
  55574. for (name in source.matrices2x2) {
  55575. material.setMatrix2x2(name, source.matrices2x2[name]);
  55576. }
  55577. // Vector2Array
  55578. for (name in source.vectors2Arrays) {
  55579. material.setArray2(name, source.vectors2Arrays[name]);
  55580. }
  55581. // Vector3Array
  55582. for (name in source.vectors3Arrays) {
  55583. material.setArray3(name, source.vectors3Arrays[name]);
  55584. }
  55585. return material;
  55586. };
  55587. return ShaderMaterial;
  55588. }(BABYLON.Material));
  55589. BABYLON.ShaderMaterial = ShaderMaterial;
  55590. })(BABYLON || (BABYLON = {}));
  55591. //# sourceMappingURL=babylon.shaderMaterial.js.map
  55592. "use strict";
  55593. var BABYLON;
  55594. (function (BABYLON) {
  55595. var GroundMesh = /** @class */ (function (_super) {
  55596. __extends(GroundMesh, _super);
  55597. function GroundMesh(name, scene) {
  55598. var _this = _super.call(this, name, scene) || this;
  55599. _this.generateOctree = false;
  55600. return _this;
  55601. }
  55602. GroundMesh.prototype.getClassName = function () {
  55603. return "GroundMesh";
  55604. };
  55605. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  55606. get: function () {
  55607. return Math.min(this._subdivisionsX, this._subdivisionsY);
  55608. },
  55609. enumerable: true,
  55610. configurable: true
  55611. });
  55612. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  55613. get: function () {
  55614. return this._subdivisionsX;
  55615. },
  55616. enumerable: true,
  55617. configurable: true
  55618. });
  55619. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  55620. get: function () {
  55621. return this._subdivisionsY;
  55622. },
  55623. enumerable: true,
  55624. configurable: true
  55625. });
  55626. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  55627. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  55628. this._subdivisionsX = chunksCount;
  55629. this._subdivisionsY = chunksCount;
  55630. this.subdivide(chunksCount);
  55631. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  55632. };
  55633. /**
  55634. * Returns a height (y) value in the Worl system :
  55635. * the ground altitude at the coordinates (x, z) expressed in the World system.
  55636. * Returns the ground y position if (x, z) are outside the ground surface.
  55637. */
  55638. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  55639. var world = this.getWorldMatrix();
  55640. var invMat = BABYLON.Tmp.Matrix[5];
  55641. world.invertToRef(invMat);
  55642. var tmpVect = BABYLON.Tmp.Vector3[8];
  55643. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  55644. x = tmpVect.x;
  55645. z = tmpVect.z;
  55646. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55647. return this.position.y;
  55648. }
  55649. if (!this._heightQuads || this._heightQuads.length == 0) {
  55650. this._initHeightQuads();
  55651. this._computeHeightQuads();
  55652. }
  55653. var facet = this._getFacetAt(x, z);
  55654. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  55655. // return y in the World system
  55656. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  55657. return tmpVect.y;
  55658. };
  55659. /**
  55660. * Returns a normalized vector (Vector3) orthogonal to the ground
  55661. * at the ground coordinates (x, z) expressed in the World system.
  55662. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  55663. */
  55664. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  55665. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  55666. this.getNormalAtCoordinatesToRef(x, z, normal);
  55667. return normal;
  55668. };
  55669. /**
  55670. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  55671. * at the ground coordinates (x, z) expressed in the World system.
  55672. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  55673. * Returns the GroundMesh.
  55674. */
  55675. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  55676. var world = this.getWorldMatrix();
  55677. var tmpMat = BABYLON.Tmp.Matrix[5];
  55678. world.invertToRef(tmpMat);
  55679. var tmpVect = BABYLON.Tmp.Vector3[8];
  55680. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  55681. x = tmpVect.x;
  55682. z = tmpVect.z;
  55683. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55684. return this;
  55685. }
  55686. if (!this._heightQuads || this._heightQuads.length == 0) {
  55687. this._initHeightQuads();
  55688. this._computeHeightQuads();
  55689. }
  55690. var facet = this._getFacetAt(x, z);
  55691. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  55692. return this;
  55693. };
  55694. /**
  55695. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  55696. * if the ground has been updated.
  55697. * This can be used in the render loop.
  55698. * Returns the GroundMesh.
  55699. */
  55700. GroundMesh.prototype.updateCoordinateHeights = function () {
  55701. if (!this._heightQuads || this._heightQuads.length == 0) {
  55702. this._initHeightQuads();
  55703. }
  55704. this._computeHeightQuads();
  55705. return this;
  55706. };
  55707. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  55708. GroundMesh.prototype._getFacetAt = function (x, z) {
  55709. // retrieve col and row from x, z coordinates in the ground local system
  55710. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  55711. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  55712. var quad = this._heightQuads[row * this._subdivisionsX + col];
  55713. var facet;
  55714. if (z < quad.slope.x * x + quad.slope.y) {
  55715. facet = quad.facet1;
  55716. }
  55717. else {
  55718. facet = quad.facet2;
  55719. }
  55720. return facet;
  55721. };
  55722. // Creates and populates the heightMap array with "facet" elements :
  55723. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  55724. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55725. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55726. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55727. // Returns the GroundMesh.
  55728. GroundMesh.prototype._initHeightQuads = function () {
  55729. var subdivisionsX = this._subdivisionsX;
  55730. var subdivisionsY = this._subdivisionsY;
  55731. this._heightQuads = new Array();
  55732. for (var row = 0; row < subdivisionsY; row++) {
  55733. for (var col = 0; col < subdivisionsX; col++) {
  55734. 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) };
  55735. this._heightQuads[row * subdivisionsX + col] = quad;
  55736. }
  55737. }
  55738. return this;
  55739. };
  55740. // Compute each quad element values and update the the heightMap array :
  55741. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55742. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55743. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55744. // Returns the GroundMesh.
  55745. GroundMesh.prototype._computeHeightQuads = function () {
  55746. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55747. if (!positions) {
  55748. return this;
  55749. }
  55750. var v1 = BABYLON.Tmp.Vector3[3];
  55751. var v2 = BABYLON.Tmp.Vector3[2];
  55752. var v3 = BABYLON.Tmp.Vector3[1];
  55753. var v4 = BABYLON.Tmp.Vector3[0];
  55754. var v1v2 = BABYLON.Tmp.Vector3[4];
  55755. var v1v3 = BABYLON.Tmp.Vector3[5];
  55756. var v1v4 = BABYLON.Tmp.Vector3[6];
  55757. var norm1 = BABYLON.Tmp.Vector3[7];
  55758. var norm2 = BABYLON.Tmp.Vector3[8];
  55759. var i = 0;
  55760. var j = 0;
  55761. var k = 0;
  55762. var cd = 0; // 2D slope coefficient : z = cd * x + h
  55763. var h = 0;
  55764. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  55765. var d2 = 0;
  55766. var subdivisionsX = this._subdivisionsX;
  55767. var subdivisionsY = this._subdivisionsY;
  55768. for (var row = 0; row < subdivisionsY; row++) {
  55769. for (var col = 0; col < subdivisionsX; col++) {
  55770. i = col * 3;
  55771. j = row * (subdivisionsX + 1) * 3;
  55772. k = (row + 1) * (subdivisionsX + 1) * 3;
  55773. v1.x = positions[j + i];
  55774. v1.y = positions[j + i + 1];
  55775. v1.z = positions[j + i + 2];
  55776. v2.x = positions[j + i + 3];
  55777. v2.y = positions[j + i + 4];
  55778. v2.z = positions[j + i + 5];
  55779. v3.x = positions[k + i];
  55780. v3.y = positions[k + i + 1];
  55781. v3.z = positions[k + i + 2];
  55782. v4.x = positions[k + i + 3];
  55783. v4.y = positions[k + i + 4];
  55784. v4.z = positions[k + i + 5];
  55785. // 2D slope V1V4
  55786. cd = (v4.z - v1.z) / (v4.x - v1.x);
  55787. h = v1.z - cd * v1.x; // v1 belongs to the slope
  55788. // facet equations :
  55789. // we compute each facet normal vector
  55790. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  55791. // we compute the value d by applying the equation to v1 which belongs to the plane
  55792. // then we store the facet equation in a Vector4
  55793. v2.subtractToRef(v1, v1v2);
  55794. v3.subtractToRef(v1, v1v3);
  55795. v4.subtractToRef(v1, v1v4);
  55796. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  55797. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  55798. norm1.normalize();
  55799. norm2.normalize();
  55800. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  55801. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  55802. var quad = this._heightQuads[row * subdivisionsX + col];
  55803. quad.slope.copyFromFloats(cd, h);
  55804. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  55805. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  55806. }
  55807. }
  55808. return this;
  55809. };
  55810. GroundMesh.prototype.serialize = function (serializationObject) {
  55811. _super.prototype.serialize.call(this, serializationObject);
  55812. serializationObject.subdivisionsX = this._subdivisionsX;
  55813. serializationObject.subdivisionsY = this._subdivisionsY;
  55814. serializationObject.minX = this._minX;
  55815. serializationObject.maxX = this._maxX;
  55816. serializationObject.minZ = this._minZ;
  55817. serializationObject.maxZ = this._maxZ;
  55818. serializationObject.width = this._width;
  55819. serializationObject.height = this._height;
  55820. };
  55821. GroundMesh.Parse = function (parsedMesh, scene) {
  55822. var result = new GroundMesh(parsedMesh.name, scene);
  55823. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  55824. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  55825. result._minX = parsedMesh.minX;
  55826. result._maxX = parsedMesh.maxX;
  55827. result._minZ = parsedMesh.minZ;
  55828. result._maxZ = parsedMesh.maxZ;
  55829. result._width = parsedMesh.width;
  55830. result._height = parsedMesh.height;
  55831. return result;
  55832. };
  55833. return GroundMesh;
  55834. }(BABYLON.Mesh));
  55835. BABYLON.GroundMesh = GroundMesh;
  55836. })(BABYLON || (BABYLON = {}));
  55837. //# sourceMappingURL=babylon.groundMesh.js.map
  55838. "use strict";
  55839. var BABYLON;
  55840. (function (BABYLON) {
  55841. /**
  55842. * Creates an instance based on a source mesh.
  55843. */
  55844. var InstancedMesh = /** @class */ (function (_super) {
  55845. __extends(InstancedMesh, _super);
  55846. function InstancedMesh(name, source) {
  55847. var _this = _super.call(this, name, source.getScene()) || this;
  55848. source.instances.push(_this);
  55849. _this._sourceMesh = source;
  55850. _this.position.copyFrom(source.position);
  55851. _this.rotation.copyFrom(source.rotation);
  55852. _this.scaling.copyFrom(source.scaling);
  55853. if (source.rotationQuaternion) {
  55854. _this.rotationQuaternion = source.rotationQuaternion.clone();
  55855. }
  55856. _this.infiniteDistance = source.infiniteDistance;
  55857. _this.setPivotMatrix(source.getPivotMatrix());
  55858. _this.refreshBoundingInfo();
  55859. _this._syncSubMeshes();
  55860. return _this;
  55861. }
  55862. /**
  55863. * Returns the string "InstancedMesh".
  55864. */
  55865. InstancedMesh.prototype.getClassName = function () {
  55866. return "InstancedMesh";
  55867. };
  55868. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  55869. // Methods
  55870. get: function () {
  55871. return this._sourceMesh.receiveShadows;
  55872. },
  55873. enumerable: true,
  55874. configurable: true
  55875. });
  55876. Object.defineProperty(InstancedMesh.prototype, "material", {
  55877. get: function () {
  55878. return this._sourceMesh.material;
  55879. },
  55880. enumerable: true,
  55881. configurable: true
  55882. });
  55883. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  55884. get: function () {
  55885. return this._sourceMesh.visibility;
  55886. },
  55887. enumerable: true,
  55888. configurable: true
  55889. });
  55890. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  55891. get: function () {
  55892. return this._sourceMesh.skeleton;
  55893. },
  55894. enumerable: true,
  55895. configurable: true
  55896. });
  55897. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  55898. get: function () {
  55899. return this._sourceMesh.renderingGroupId;
  55900. },
  55901. set: function (value) {
  55902. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  55903. return;
  55904. }
  55905. //no-op with warning
  55906. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  55907. },
  55908. enumerable: true,
  55909. configurable: true
  55910. });
  55911. /**
  55912. * Returns the total number of vertices (integer).
  55913. */
  55914. InstancedMesh.prototype.getTotalVertices = function () {
  55915. return this._sourceMesh.getTotalVertices();
  55916. };
  55917. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  55918. get: function () {
  55919. return this._sourceMesh;
  55920. },
  55921. enumerable: true,
  55922. configurable: true
  55923. });
  55924. /**
  55925. * Is this node ready to be used/rendered
  55926. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  55927. * @return {boolean} is it ready
  55928. */
  55929. InstancedMesh.prototype.isReady = function (completeCheck) {
  55930. if (completeCheck === void 0) { completeCheck = false; }
  55931. return this._sourceMesh.isReady(completeCheck, true);
  55932. };
  55933. /**
  55934. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  55935. */
  55936. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  55937. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  55938. };
  55939. /**
  55940. * Sets the vertex data of the mesh geometry for the requested `kind`.
  55941. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  55942. * The `data` are either a numeric array either a Float32Array.
  55943. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  55944. * 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).
  55945. * Note that a new underlying VertexBuffer object is created each call.
  55946. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  55947. *
  55948. * Possible `kind` values :
  55949. * - BABYLON.VertexBuffer.PositionKind
  55950. * - BABYLON.VertexBuffer.UVKind
  55951. * - BABYLON.VertexBuffer.UV2Kind
  55952. * - BABYLON.VertexBuffer.UV3Kind
  55953. * - BABYLON.VertexBuffer.UV4Kind
  55954. * - BABYLON.VertexBuffer.UV5Kind
  55955. * - BABYLON.VertexBuffer.UV6Kind
  55956. * - BABYLON.VertexBuffer.ColorKind
  55957. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55958. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55959. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55960. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55961. *
  55962. * Returns the Mesh.
  55963. */
  55964. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  55965. if (this.sourceMesh) {
  55966. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  55967. }
  55968. return this.sourceMesh;
  55969. };
  55970. /**
  55971. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  55972. * If the mesh has no geometry, it is simply returned as it is.
  55973. * The `data` are either a numeric array either a Float32Array.
  55974. * No new underlying VertexBuffer object is created.
  55975. * 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.
  55976. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  55977. *
  55978. * Possible `kind` values :
  55979. * - BABYLON.VertexBuffer.PositionKind
  55980. * - BABYLON.VertexBuffer.UVKind
  55981. * - BABYLON.VertexBuffer.UV2Kind
  55982. * - BABYLON.VertexBuffer.UV3Kind
  55983. * - BABYLON.VertexBuffer.UV4Kind
  55984. * - BABYLON.VertexBuffer.UV5Kind
  55985. * - BABYLON.VertexBuffer.UV6Kind
  55986. * - BABYLON.VertexBuffer.ColorKind
  55987. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55988. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55989. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55990. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55991. *
  55992. * Returns the Mesh.
  55993. */
  55994. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  55995. if (this.sourceMesh) {
  55996. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  55997. }
  55998. return this.sourceMesh;
  55999. };
  56000. /**
  56001. * Sets the mesh indices.
  56002. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  56003. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  56004. * This method creates a new index buffer each call.
  56005. * Returns the Mesh.
  56006. */
  56007. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  56008. if (totalVertices === void 0) { totalVertices = null; }
  56009. if (this.sourceMesh) {
  56010. this.sourceMesh.setIndices(indices, totalVertices);
  56011. }
  56012. return this.sourceMesh;
  56013. };
  56014. /**
  56015. * Boolean : True if the mesh owns the requested kind of data.
  56016. */
  56017. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  56018. return this._sourceMesh.isVerticesDataPresent(kind);
  56019. };
  56020. /**
  56021. * Returns an array of indices (IndicesArray).
  56022. */
  56023. InstancedMesh.prototype.getIndices = function () {
  56024. return this._sourceMesh.getIndices();
  56025. };
  56026. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  56027. get: function () {
  56028. return this._sourceMesh._positions;
  56029. },
  56030. enumerable: true,
  56031. configurable: true
  56032. });
  56033. /**
  56034. * Sets a new updated BoundingInfo to the mesh.
  56035. * Returns the mesh.
  56036. */
  56037. InstancedMesh.prototype.refreshBoundingInfo = function () {
  56038. var meshBB = this._sourceMesh.getBoundingInfo();
  56039. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  56040. this._updateBoundingInfo();
  56041. return this;
  56042. };
  56043. InstancedMesh.prototype._preActivate = function () {
  56044. if (this._currentLOD) {
  56045. this._currentLOD._preActivate();
  56046. }
  56047. return this;
  56048. };
  56049. InstancedMesh.prototype._activate = function (renderId) {
  56050. if (this._currentLOD) {
  56051. this._currentLOD._registerInstanceForRenderId(this, renderId);
  56052. }
  56053. return this;
  56054. };
  56055. /**
  56056. * Returns the current associated LOD AbstractMesh.
  56057. */
  56058. InstancedMesh.prototype.getLOD = function (camera) {
  56059. if (!camera) {
  56060. return this;
  56061. }
  56062. var boundingInfo = this.getBoundingInfo();
  56063. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  56064. if (this._currentLOD === this.sourceMesh) {
  56065. return this;
  56066. }
  56067. return this._currentLOD;
  56068. };
  56069. InstancedMesh.prototype._syncSubMeshes = function () {
  56070. this.releaseSubMeshes();
  56071. if (this._sourceMesh.subMeshes) {
  56072. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  56073. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  56074. }
  56075. }
  56076. return this;
  56077. };
  56078. InstancedMesh.prototype._generatePointsArray = function () {
  56079. return this._sourceMesh._generatePointsArray();
  56080. };
  56081. /**
  56082. * Creates a new InstancedMesh from the current mesh.
  56083. * - name (string) : the cloned mesh name
  56084. * - newParent (optional Node) : the optional Node to parent the clone to.
  56085. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  56086. *
  56087. * Returns the clone.
  56088. */
  56089. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56090. var result = this._sourceMesh.createInstance(name);
  56091. // Deep copy
  56092. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  56093. // Bounding info
  56094. this.refreshBoundingInfo();
  56095. // Parent
  56096. if (newParent) {
  56097. result.parent = newParent;
  56098. }
  56099. if (!doNotCloneChildren) {
  56100. // Children
  56101. for (var index = 0; index < this.getScene().meshes.length; index++) {
  56102. var mesh = this.getScene().meshes[index];
  56103. if (mesh.parent === this) {
  56104. mesh.clone(mesh.name, result);
  56105. }
  56106. }
  56107. }
  56108. result.computeWorldMatrix(true);
  56109. return result;
  56110. };
  56111. /**
  56112. * Disposes the InstancedMesh.
  56113. * Returns nothing.
  56114. */
  56115. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  56116. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  56117. // Remove from mesh
  56118. var index = this._sourceMesh.instances.indexOf(this);
  56119. this._sourceMesh.instances.splice(index, 1);
  56120. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  56121. };
  56122. return InstancedMesh;
  56123. }(BABYLON.AbstractMesh));
  56124. BABYLON.InstancedMesh = InstancedMesh;
  56125. })(BABYLON || (BABYLON = {}));
  56126. //# sourceMappingURL=babylon.instancedMesh.js.map
  56127. "use strict";
  56128. var BABYLON;
  56129. (function (BABYLON) {
  56130. var LinesMesh = /** @class */ (function (_super) {
  56131. __extends(LinesMesh, _super);
  56132. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  56133. if (scene === void 0) { scene = null; }
  56134. if (parent === void 0) { parent = null; }
  56135. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  56136. _this.useVertexColor = useVertexColor;
  56137. _this.useVertexAlpha = useVertexAlpha;
  56138. _this.color = new BABYLON.Color3(1, 1, 1);
  56139. _this.alpha = 1;
  56140. if (source) {
  56141. _this.color = source.color.clone();
  56142. _this.alpha = source.alpha;
  56143. _this.useVertexColor = source.useVertexColor;
  56144. _this.useVertexAlpha = source.useVertexAlpha;
  56145. }
  56146. _this._intersectionThreshold = 0.1;
  56147. var defines = [];
  56148. var options = {
  56149. attributes: [BABYLON.VertexBuffer.PositionKind],
  56150. uniforms: ["world", "viewProjection"],
  56151. needAlphaBlending: true,
  56152. defines: defines
  56153. };
  56154. if (useVertexAlpha === false) {
  56155. options.needAlphaBlending = false;
  56156. }
  56157. if (!useVertexColor) {
  56158. options.uniforms.push("color");
  56159. }
  56160. else {
  56161. options.defines.push("#define VERTEXCOLOR");
  56162. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  56163. }
  56164. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  56165. return _this;
  56166. }
  56167. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  56168. /**
  56169. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56170. * This margin is expressed in world space coordinates, so its value may vary.
  56171. * Default value is 0.1
  56172. * @returns the intersection Threshold value.
  56173. */
  56174. get: function () {
  56175. return this._intersectionThreshold;
  56176. },
  56177. /**
  56178. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56179. * This margin is expressed in world space coordinates, so its value may vary.
  56180. * @param value the new threshold to apply
  56181. */
  56182. set: function (value) {
  56183. if (this._intersectionThreshold === value) {
  56184. return;
  56185. }
  56186. this._intersectionThreshold = value;
  56187. if (this.geometry) {
  56188. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  56189. }
  56190. },
  56191. enumerable: true,
  56192. configurable: true
  56193. });
  56194. /**
  56195. * Returns the string "LineMesh"
  56196. */
  56197. LinesMesh.prototype.getClassName = function () {
  56198. return "LinesMesh";
  56199. };
  56200. Object.defineProperty(LinesMesh.prototype, "material", {
  56201. get: function () {
  56202. return this._colorShader;
  56203. },
  56204. set: function (value) {
  56205. // Do nothing
  56206. },
  56207. enumerable: true,
  56208. configurable: true
  56209. });
  56210. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  56211. get: function () {
  56212. return false;
  56213. },
  56214. enumerable: true,
  56215. configurable: true
  56216. });
  56217. LinesMesh.prototype.createInstance = function (name) {
  56218. throw new Error("LinesMeshes do not support createInstance.");
  56219. };
  56220. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  56221. if (!this._geometry) {
  56222. return this;
  56223. }
  56224. // VBOs
  56225. this._geometry._bind(this._colorShader.getEffect());
  56226. // Color
  56227. if (!this.useVertexColor) {
  56228. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  56229. }
  56230. return this;
  56231. };
  56232. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  56233. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  56234. return this;
  56235. }
  56236. var engine = this.getScene().getEngine();
  56237. // Draw order
  56238. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  56239. return this;
  56240. };
  56241. LinesMesh.prototype.dispose = function (doNotRecurse) {
  56242. this._colorShader.dispose();
  56243. _super.prototype.dispose.call(this, doNotRecurse);
  56244. };
  56245. /**
  56246. * Returns a new LineMesh object cloned from the current one.
  56247. */
  56248. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56249. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  56250. };
  56251. return LinesMesh;
  56252. }(BABYLON.Mesh));
  56253. BABYLON.LinesMesh = LinesMesh;
  56254. })(BABYLON || (BABYLON = {}));
  56255. //# sourceMappingURL=babylon.linesMesh.js.map
  56256. "use strict";
  56257. var BABYLON;
  56258. (function (BABYLON) {
  56259. var MeshBuilder = /** @class */ (function () {
  56260. function MeshBuilder() {
  56261. }
  56262. MeshBuilder.updateSideOrientation = function (orientation) {
  56263. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  56264. return BABYLON.Mesh.DOUBLESIDE;
  56265. }
  56266. if (orientation === undefined || orientation === null) {
  56267. return BABYLON.Mesh.FRONTSIDE;
  56268. }
  56269. return orientation;
  56270. };
  56271. /**
  56272. * Creates a box mesh.
  56273. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  56274. * The parameter `size` sets the size (float) of each box side (default 1).
  56275. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  56276. * 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).
  56277. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56278. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56279. * 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).
  56280. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56281. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56282. */
  56283. MeshBuilder.CreateBox = function (name, options, scene) {
  56284. if (scene === void 0) { scene = null; }
  56285. var box = new BABYLON.Mesh(name, scene);
  56286. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56287. box._originalBuilderSideOrientation = options.sideOrientation;
  56288. var vertexData = BABYLON.VertexData.CreateBox(options);
  56289. vertexData.applyToMesh(box, options.updatable);
  56290. return box;
  56291. };
  56292. /**
  56293. * Creates a sphere mesh.
  56294. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  56295. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  56296. * 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`).
  56297. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  56298. * 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
  56299. * 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).
  56300. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56301. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  56302. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56303. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56304. */
  56305. MeshBuilder.CreateSphere = function (name, options, scene) {
  56306. var sphere = new BABYLON.Mesh(name, scene);
  56307. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56308. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56309. var vertexData = BABYLON.VertexData.CreateSphere(options);
  56310. vertexData.applyToMesh(sphere, options.updatable);
  56311. return sphere;
  56312. };
  56313. /**
  56314. * Creates a plane polygonal mesh. By default, this is a disc.
  56315. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  56316. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  56317. * 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.
  56318. * 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
  56319. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56320. * 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).
  56321. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56322. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56323. */
  56324. MeshBuilder.CreateDisc = function (name, options, scene) {
  56325. if (scene === void 0) { scene = null; }
  56326. var disc = new BABYLON.Mesh(name, scene);
  56327. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56328. disc._originalBuilderSideOrientation = options.sideOrientation;
  56329. var vertexData = BABYLON.VertexData.CreateDisc(options);
  56330. vertexData.applyToMesh(disc, options.updatable);
  56331. return disc;
  56332. };
  56333. /**
  56334. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  56335. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  56336. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  56337. * 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`).
  56338. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  56339. * 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.
  56340. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56341. * 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).
  56342. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56343. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56344. */
  56345. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  56346. var sphere = new BABYLON.Mesh(name, scene);
  56347. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56348. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56349. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  56350. vertexData.applyToMesh(sphere, options.updatable);
  56351. return sphere;
  56352. };
  56353. ;
  56354. /**
  56355. * Creates a ribbon mesh.
  56356. * 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.
  56357. *
  56358. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  56359. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  56360. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  56361. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  56362. * 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.
  56363. * 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.
  56364. * 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
  56365. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56366. * 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).
  56367. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56368. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56369. * 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.
  56370. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  56371. * 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
  56372. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  56373. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  56374. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56375. */
  56376. MeshBuilder.CreateRibbon = function (name, options, scene) {
  56377. if (scene === void 0) { scene = null; }
  56378. var pathArray = options.pathArray;
  56379. var closeArray = options.closeArray;
  56380. var closePath = options.closePath;
  56381. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56382. var instance = options.instance;
  56383. var updatable = options.updatable;
  56384. if (instance) {
  56385. // positionFunction : ribbon case
  56386. // only pathArray and sideOrientation parameters are taken into account for positions update
  56387. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  56388. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  56389. var positionFunction = function (positions) {
  56390. var minlg = pathArray[0].length;
  56391. var i = 0;
  56392. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  56393. for (var si = 1; si <= ns; si++) {
  56394. for (var p = 0; p < pathArray.length; p++) {
  56395. var path = pathArray[p];
  56396. var l = path.length;
  56397. minlg = (minlg < l) ? minlg : l;
  56398. var j = 0;
  56399. while (j < minlg) {
  56400. positions[i] = path[j].x;
  56401. positions[i + 1] = path[j].y;
  56402. positions[i + 2] = path[j].z;
  56403. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  56404. BABYLON.Tmp.Vector3[0].x = path[j].x;
  56405. }
  56406. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  56407. BABYLON.Tmp.Vector3[1].x = path[j].x;
  56408. }
  56409. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  56410. BABYLON.Tmp.Vector3[0].y = path[j].y;
  56411. }
  56412. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  56413. BABYLON.Tmp.Vector3[1].y = path[j].y;
  56414. }
  56415. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  56416. BABYLON.Tmp.Vector3[0].z = path[j].z;
  56417. }
  56418. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  56419. BABYLON.Tmp.Vector3[1].z = path[j].z;
  56420. }
  56421. j++;
  56422. i += 3;
  56423. }
  56424. if (instance._closePath) {
  56425. positions[i] = path[0].x;
  56426. positions[i + 1] = path[0].y;
  56427. positions[i + 2] = path[0].z;
  56428. i += 3;
  56429. }
  56430. }
  56431. }
  56432. };
  56433. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56434. positionFunction(positions);
  56435. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  56436. instance._boundingInfo.update(instance._worldMatrix);
  56437. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56438. if (options.colors) {
  56439. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56440. for (var c = 0; c < options.colors.length; c++) {
  56441. colors[c * 4] = options.colors[c].r;
  56442. colors[c * 4 + 1] = options.colors[c].g;
  56443. colors[c * 4 + 2] = options.colors[c].b;
  56444. colors[c * 4 + 3] = options.colors[c].a;
  56445. }
  56446. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  56447. }
  56448. if (options.uvs) {
  56449. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56450. for (var i = 0; i < options.uvs.length; i++) {
  56451. uvs[i * 2] = options.uvs[i].x;
  56452. uvs[i * 2 + 1] = options.uvs[i].y;
  56453. }
  56454. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  56455. }
  56456. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  56457. var indices = instance.getIndices();
  56458. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56459. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  56460. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  56461. if (instance._closePath) {
  56462. var indexFirst = 0;
  56463. var indexLast = 0;
  56464. for (var p = 0; p < pathArray.length; p++) {
  56465. indexFirst = instance._idx[p] * 3;
  56466. if (p + 1 < pathArray.length) {
  56467. indexLast = (instance._idx[p + 1] - 1) * 3;
  56468. }
  56469. else {
  56470. indexLast = normals.length - 3;
  56471. }
  56472. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  56473. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  56474. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  56475. normals[indexLast] = normals[indexFirst];
  56476. normals[indexLast + 1] = normals[indexFirst + 1];
  56477. normals[indexLast + 2] = normals[indexFirst + 2];
  56478. }
  56479. }
  56480. if (!(instance.areNormalsFrozen)) {
  56481. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  56482. }
  56483. }
  56484. return instance;
  56485. }
  56486. else {
  56487. var ribbon = new BABYLON.Mesh(name, scene);
  56488. ribbon._originalBuilderSideOrientation = sideOrientation;
  56489. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  56490. if (closePath) {
  56491. ribbon._idx = vertexData._idx;
  56492. }
  56493. ribbon._closePath = closePath;
  56494. ribbon._closeArray = closeArray;
  56495. vertexData.applyToMesh(ribbon, updatable);
  56496. return ribbon;
  56497. }
  56498. };
  56499. /**
  56500. * Creates a cylinder or a cone mesh.
  56501. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  56502. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  56503. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  56504. * 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.
  56505. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  56506. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  56507. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  56508. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  56509. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  56510. * 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).
  56511. * 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
  56512. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  56513. * 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
  56514. * 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.
  56515. * If `enclose` is false, a ring surface is one element.
  56516. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  56517. * 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
  56518. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56519. * 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).
  56520. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56521. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56522. */
  56523. MeshBuilder.CreateCylinder = function (name, options, scene) {
  56524. var cylinder = new BABYLON.Mesh(name, scene);
  56525. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56526. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  56527. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  56528. vertexData.applyToMesh(cylinder, options.updatable);
  56529. return cylinder;
  56530. };
  56531. /**
  56532. * Creates a torus mesh.
  56533. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  56534. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  56535. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  56536. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  56537. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56538. * 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).
  56539. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56540. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56541. */
  56542. MeshBuilder.CreateTorus = function (name, options, scene) {
  56543. var torus = new BABYLON.Mesh(name, scene);
  56544. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56545. torus._originalBuilderSideOrientation = options.sideOrientation;
  56546. var vertexData = BABYLON.VertexData.CreateTorus(options);
  56547. vertexData.applyToMesh(torus, options.updatable);
  56548. return torus;
  56549. };
  56550. /**
  56551. * Creates a torus knot mesh.
  56552. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  56553. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  56554. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  56555. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  56556. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  56557. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56558. * 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).
  56559. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56560. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56561. */
  56562. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  56563. var torusKnot = new BABYLON.Mesh(name, scene);
  56564. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56565. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  56566. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  56567. vertexData.applyToMesh(torusKnot, options.updatable);
  56568. return torusKnot;
  56569. };
  56570. /**
  56571. * Creates a line system mesh.
  56572. * A line system is a pool of many lines gathered in a single mesh.
  56573. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  56574. * 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.
  56575. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  56576. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  56577. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  56578. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  56579. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  56580. * 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
  56581. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  56582. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56583. */
  56584. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  56585. var instance = options.instance;
  56586. var lines = options.lines;
  56587. var colors = options.colors;
  56588. if (instance) {
  56589. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56590. var vertexColor;
  56591. var lineColors;
  56592. if (colors) {
  56593. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56594. }
  56595. var i = 0;
  56596. var c = 0;
  56597. for (var l = 0; l < lines.length; l++) {
  56598. var points = lines[l];
  56599. for (var p = 0; p < points.length; p++) {
  56600. positions[i] = points[p].x;
  56601. positions[i + 1] = points[p].y;
  56602. positions[i + 2] = points[p].z;
  56603. if (colors && vertexColor) {
  56604. lineColors = colors[l];
  56605. vertexColor[c] = lineColors[p].r;
  56606. vertexColor[c + 1] = lineColors[p].g;
  56607. vertexColor[c + 2] = lineColors[p].b;
  56608. vertexColor[c + 3] = lineColors[p].a;
  56609. c += 4;
  56610. }
  56611. i += 3;
  56612. }
  56613. }
  56614. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56615. if (colors && vertexColor) {
  56616. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  56617. }
  56618. return instance;
  56619. }
  56620. // line system creation
  56621. var useVertexColor = (colors) ? true : false;
  56622. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  56623. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  56624. vertexData.applyToMesh(lineSystem, options.updatable);
  56625. return lineSystem;
  56626. };
  56627. /**
  56628. * Creates a line mesh.
  56629. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  56630. * 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.
  56631. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56632. * The parameter `points` is an array successive Vector3.
  56633. * 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
  56634. * The optional parameter `colors` is an array of successive Color4, one per line point.
  56635. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  56636. * When updating an instance, remember that only point positions can change, not the number of points.
  56637. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56638. */
  56639. MeshBuilder.CreateLines = function (name, options, scene) {
  56640. if (scene === void 0) { scene = null; }
  56641. var colors = (options.colors) ? [options.colors] : null;
  56642. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  56643. return lines;
  56644. };
  56645. /**
  56646. * Creates a dashed line mesh.
  56647. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  56648. * 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.
  56649. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56650. * The parameter `points` is an array successive Vector3.
  56651. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  56652. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  56653. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  56654. * 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
  56655. * When updating an instance, remember that only point positions can change, not the number of points.
  56656. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56657. */
  56658. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  56659. if (scene === void 0) { scene = null; }
  56660. var points = options.points;
  56661. var instance = options.instance;
  56662. var gapSize = options.gapSize || 1;
  56663. var dashSize = options.dashSize || 3;
  56664. if (instance) {
  56665. var positionFunction = function (positions) {
  56666. var curvect = BABYLON.Vector3.Zero();
  56667. var nbSeg = positions.length / 6;
  56668. var lg = 0;
  56669. var nb = 0;
  56670. var shft = 0;
  56671. var dashshft = 0;
  56672. var curshft = 0;
  56673. var p = 0;
  56674. var i = 0;
  56675. var j = 0;
  56676. for (i = 0; i < points.length - 1; i++) {
  56677. points[i + 1].subtractToRef(points[i], curvect);
  56678. lg += curvect.length();
  56679. }
  56680. shft = lg / nbSeg;
  56681. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  56682. for (i = 0; i < points.length - 1; i++) {
  56683. points[i + 1].subtractToRef(points[i], curvect);
  56684. nb = Math.floor(curvect.length() / shft);
  56685. curvect.normalize();
  56686. j = 0;
  56687. while (j < nb && p < positions.length) {
  56688. curshft = shft * j;
  56689. positions[p] = points[i].x + curshft * curvect.x;
  56690. positions[p + 1] = points[i].y + curshft * curvect.y;
  56691. positions[p + 2] = points[i].z + curshft * curvect.z;
  56692. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  56693. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  56694. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  56695. p += 6;
  56696. j++;
  56697. }
  56698. }
  56699. while (p < positions.length) {
  56700. positions[p] = points[i].x;
  56701. positions[p + 1] = points[i].y;
  56702. positions[p + 2] = points[i].z;
  56703. p += 3;
  56704. }
  56705. };
  56706. instance.updateMeshPositions(positionFunction, false);
  56707. return instance;
  56708. }
  56709. // dashed lines creation
  56710. var dashedLines = new BABYLON.LinesMesh(name, scene);
  56711. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  56712. vertexData.applyToMesh(dashedLines, options.updatable);
  56713. dashedLines.dashSize = dashSize;
  56714. dashedLines.gapSize = gapSize;
  56715. return dashedLines;
  56716. };
  56717. /**
  56718. * Creates an extruded shape mesh.
  56719. * 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.
  56720. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  56721. *
  56722. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56723. * 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
  56724. * extruded along the Z axis.
  56725. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56726. * 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.
  56727. * The parameter `scale` (float, default 1) is the value to scale the shape.
  56728. * 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
  56729. * 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
  56730. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56731. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56732. * 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).
  56733. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56734. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56735. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56736. */
  56737. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  56738. if (scene === void 0) { scene = null; }
  56739. var path = options.path;
  56740. var shape = options.shape;
  56741. var scale = options.scale || 1;
  56742. var rotation = options.rotation || 0;
  56743. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56744. var updatable = options.updatable;
  56745. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56746. var instance = options.instance || null;
  56747. var invertUV = options.invertUV || false;
  56748. 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);
  56749. };
  56750. /**
  56751. * Creates an custom extruded shape mesh.
  56752. * 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.
  56753. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  56754. *
  56755. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56756. * 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
  56757. * extruded along the Z axis.
  56758. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56759. * 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
  56760. * and the distance of this point from the begining of the path :
  56761. * ```javascript
  56762. * var rotationFunction = function(i, distance) {
  56763. * // do things
  56764. * return rotationValue; }
  56765. * ```
  56766. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  56767. * 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
  56768. * and the distance of this point from the begining of the path :
  56769. * ```javascript
  56770. * var scaleFunction = function(i, distance) {
  56771. * // do things
  56772. * return scaleValue;}
  56773. * ```
  56774. * It must returns a float value that will be the scale value applied to the shape on each path point.
  56775. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  56776. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  56777. * 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
  56778. * 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
  56779. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56780. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56781. * 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).
  56782. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56783. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56784. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56785. */
  56786. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  56787. var path = options.path;
  56788. var shape = options.shape;
  56789. var scaleFunction = options.scaleFunction || (function () { return 1; });
  56790. var rotationFunction = options.rotationFunction || (function () { return 0; });
  56791. var ribbonCloseArray = options.ribbonCloseArray || false;
  56792. var ribbonClosePath = options.ribbonClosePath || false;
  56793. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56794. var updatable = options.updatable;
  56795. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56796. var instance = options.instance;
  56797. var invertUV = options.invertUV || false;
  56798. 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);
  56799. };
  56800. /**
  56801. * Creates lathe mesh.
  56802. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  56803. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  56804. *
  56805. * 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
  56806. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  56807. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  56808. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  56809. * 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.
  56810. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  56811. * 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
  56812. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56813. * 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).
  56814. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56815. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56816. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56817. */
  56818. MeshBuilder.CreateLathe = function (name, options, scene) {
  56819. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  56820. var closed = (options.closed === undefined) ? true : options.closed;
  56821. var shape = options.shape;
  56822. var radius = options.radius || 1;
  56823. var tessellation = options.tessellation || 64;
  56824. var updatable = options.updatable;
  56825. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56826. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56827. var pi2 = Math.PI * 2;
  56828. var paths = new Array();
  56829. var invertUV = options.invertUV || false;
  56830. var i = 0;
  56831. var p = 0;
  56832. var step = pi2 / tessellation * arc;
  56833. var rotated;
  56834. var path = new Array();
  56835. ;
  56836. for (i = 0; i <= tessellation; i++) {
  56837. var path = [];
  56838. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  56839. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  56840. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  56841. }
  56842. for (p = 0; p < shape.length; p++) {
  56843. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  56844. path.push(rotated);
  56845. }
  56846. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  56847. 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));
  56848. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  56849. }
  56850. paths.push(path);
  56851. }
  56852. // lathe ribbon
  56853. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56854. return lathe;
  56855. };
  56856. /**
  56857. * Creates a plane mesh.
  56858. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56859. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  56860. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  56861. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  56862. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56863. * 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).
  56864. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56865. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56866. */
  56867. MeshBuilder.CreatePlane = function (name, options, scene) {
  56868. var plane = new BABYLON.Mesh(name, scene);
  56869. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56870. plane._originalBuilderSideOrientation = options.sideOrientation;
  56871. var vertexData = BABYLON.VertexData.CreatePlane(options);
  56872. vertexData.applyToMesh(plane, options.updatable);
  56873. if (options.sourcePlane) {
  56874. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  56875. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  56876. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  56877. plane.rotate(vectorProduct, product);
  56878. }
  56879. return plane;
  56880. };
  56881. /**
  56882. * Creates a ground mesh.
  56883. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56884. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  56885. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  56886. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56887. */
  56888. MeshBuilder.CreateGround = function (name, options, scene) {
  56889. var ground = new BABYLON.GroundMesh(name, scene);
  56890. ground._setReady(false);
  56891. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  56892. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  56893. ground._width = options.width || 1;
  56894. ground._height = options.height || 1;
  56895. ground._maxX = ground._width / 2;
  56896. ground._maxZ = ground._height / 2;
  56897. ground._minX = -ground._maxX;
  56898. ground._minZ = -ground._maxZ;
  56899. var vertexData = BABYLON.VertexData.CreateGround(options);
  56900. vertexData.applyToMesh(ground, options.updatable);
  56901. ground._setReady(true);
  56902. return ground;
  56903. };
  56904. /**
  56905. * Creates a tiled ground mesh.
  56906. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  56907. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  56908. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  56909. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  56910. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  56911. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  56912. * numbers of subdivisions on the ground width and height of each tile.
  56913. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56914. */
  56915. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  56916. var tiledGround = new BABYLON.Mesh(name, scene);
  56917. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  56918. vertexData.applyToMesh(tiledGround, options.updatable);
  56919. return tiledGround;
  56920. };
  56921. /**
  56922. * Creates a ground mesh from a height map.
  56923. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  56924. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  56925. * The parameter `url` sets the URL of the height map image resource.
  56926. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  56927. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  56928. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  56929. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  56930. * 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.
  56931. * 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).
  56932. * This function is passed the newly built mesh :
  56933. * ```javascript
  56934. * function(mesh) { // do things
  56935. * return; }
  56936. * ```
  56937. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56938. */
  56939. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  56940. var width = options.width || 10.0;
  56941. var height = options.height || 10.0;
  56942. var subdivisions = options.subdivisions || 1 | 0;
  56943. var minHeight = options.minHeight || 0.0;
  56944. var maxHeight = options.maxHeight || 1.0;
  56945. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  56946. var updatable = options.updatable;
  56947. var onReady = options.onReady;
  56948. var ground = new BABYLON.GroundMesh(name, scene);
  56949. ground._subdivisionsX = subdivisions;
  56950. ground._subdivisionsY = subdivisions;
  56951. ground._width = width;
  56952. ground._height = height;
  56953. ground._maxX = ground._width / 2.0;
  56954. ground._maxZ = ground._height / 2.0;
  56955. ground._minX = -ground._maxX;
  56956. ground._minZ = -ground._maxZ;
  56957. ground._setReady(false);
  56958. var onload = function (img) {
  56959. // Getting height map data
  56960. var canvas = document.createElement("canvas");
  56961. var context = canvas.getContext("2d");
  56962. if (!context) {
  56963. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  56964. }
  56965. if (scene.isDisposed) {
  56966. return;
  56967. }
  56968. var bufferWidth = img.width;
  56969. var bufferHeight = img.height;
  56970. canvas.width = bufferWidth;
  56971. canvas.height = bufferHeight;
  56972. context.drawImage(img, 0, 0);
  56973. // Create VertexData from map data
  56974. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  56975. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  56976. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  56977. width: width, height: height,
  56978. subdivisions: subdivisions,
  56979. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  56980. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  56981. });
  56982. vertexData.applyToMesh(ground, updatable);
  56983. //execute ready callback, if set
  56984. if (onReady) {
  56985. onReady(ground);
  56986. }
  56987. ground._setReady(true);
  56988. };
  56989. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  56990. return ground;
  56991. };
  56992. /**
  56993. * Creates a polygon mesh.
  56994. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  56995. * 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.
  56996. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56997. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56998. * 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).
  56999. * Remember you can only change the shape positions, not their number when updating a polygon.
  57000. */
  57001. MeshBuilder.CreatePolygon = function (name, options, scene) {
  57002. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57003. var shape = options.shape;
  57004. var holes = options.holes || [];
  57005. var depth = options.depth || 0;
  57006. var contours = [];
  57007. var hole = [];
  57008. for (var i = 0; i < shape.length; i++) {
  57009. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  57010. }
  57011. var epsilon = 0.00000001;
  57012. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  57013. contours.pop();
  57014. }
  57015. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  57016. for (var hNb = 0; hNb < holes.length; hNb++) {
  57017. hole = [];
  57018. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  57019. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  57020. }
  57021. polygonTriangulation.addHole(hole);
  57022. }
  57023. var polygon = polygonTriangulation.build(options.updatable, depth);
  57024. polygon._originalBuilderSideOrientation = options.sideOrientation;
  57025. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  57026. vertexData.applyToMesh(polygon, options.updatable);
  57027. return polygon;
  57028. };
  57029. ;
  57030. /**
  57031. * Creates an extruded polygon mesh, with depth in the Y direction.
  57032. * 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).
  57033. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  57034. */
  57035. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  57036. return MeshBuilder.CreatePolygon(name, options, scene);
  57037. };
  57038. ;
  57039. /**
  57040. * Creates a tube mesh.
  57041. * 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.
  57042. *
  57043. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  57044. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  57045. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  57046. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  57047. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  57048. * 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.
  57049. * It must return a radius value (positive float) :
  57050. * ```javascript
  57051. * var radiusFunction = function(i, distance) {
  57052. * // do things
  57053. * return radius; }
  57054. * ```
  57055. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  57056. * 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
  57057. * 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
  57058. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57059. * 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).
  57060. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57061. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57062. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57063. */
  57064. MeshBuilder.CreateTube = function (name, options, scene) {
  57065. var path = options.path;
  57066. var instance = options.instance;
  57067. var radius = 1.0;
  57068. if (instance) {
  57069. radius = instance.radius;
  57070. }
  57071. if (options.radius !== undefined) {
  57072. radius = options.radius;
  57073. }
  57074. ;
  57075. var tessellation = options.tessellation || 64 | 0;
  57076. var radiusFunction = options.radiusFunction || null;
  57077. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  57078. var invertUV = options.invertUV || false;
  57079. var updatable = options.updatable;
  57080. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57081. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  57082. // tube geometry
  57083. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  57084. var tangents = path3D.getTangents();
  57085. var normals = path3D.getNormals();
  57086. var distances = path3D.getDistances();
  57087. var pi2 = Math.PI * 2;
  57088. var step = pi2 / tessellation * arc;
  57089. var returnRadius = function () { return radius; };
  57090. var radiusFunctionFinal = radiusFunction || returnRadius;
  57091. var circlePath;
  57092. var rad;
  57093. var normal;
  57094. var rotated;
  57095. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57096. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57097. for (var i = 0; i < path.length; i++) {
  57098. rad = radiusFunctionFinal(i, distances[i]); // current radius
  57099. circlePath = Array(); // current circle array
  57100. normal = normals[i]; // current normal
  57101. for (var t = 0; t < tessellation; t++) {
  57102. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  57103. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  57104. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  57105. rotated.scaleInPlace(rad).addInPlace(path[i]);
  57106. circlePath[t] = rotated;
  57107. }
  57108. circlePaths[index] = circlePath;
  57109. index++;
  57110. }
  57111. // cap
  57112. var capPath = function (nbPoints, pathIndex) {
  57113. var pointCap = Array();
  57114. for (var i = 0; i < nbPoints; i++) {
  57115. pointCap.push(path[pathIndex]);
  57116. }
  57117. return pointCap;
  57118. };
  57119. switch (cap) {
  57120. case BABYLON.Mesh.NO_CAP:
  57121. break;
  57122. case BABYLON.Mesh.CAP_START:
  57123. circlePaths[0] = capPath(tessellation, 0);
  57124. circlePaths[1] = circlePaths[2].slice(0);
  57125. break;
  57126. case BABYLON.Mesh.CAP_END:
  57127. circlePaths[index] = circlePaths[index - 1].slice(0);
  57128. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57129. break;
  57130. case BABYLON.Mesh.CAP_ALL:
  57131. circlePaths[0] = capPath(tessellation, 0);
  57132. circlePaths[1] = circlePaths[2].slice(0);
  57133. circlePaths[index] = circlePaths[index - 1].slice(0);
  57134. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57135. break;
  57136. default:
  57137. break;
  57138. }
  57139. return circlePaths;
  57140. };
  57141. var path3D;
  57142. var pathArray;
  57143. if (instance) {
  57144. var arc = options.arc || instance.arc;
  57145. path3D = (instance.path3D).update(path);
  57146. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  57147. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  57148. instance.path3D = path3D;
  57149. instance.pathArray = pathArray;
  57150. instance.arc = arc;
  57151. instance.radius = radius;
  57152. return instance;
  57153. }
  57154. // tube creation
  57155. path3D = new BABYLON.Path3D(path);
  57156. var newPathArray = new Array();
  57157. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57158. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  57159. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57160. tube.pathArray = pathArray;
  57161. tube.path3D = path3D;
  57162. tube.tessellation = tessellation;
  57163. tube.cap = cap;
  57164. tube.arc = options.arc;
  57165. tube.radius = radius;
  57166. return tube;
  57167. };
  57168. /**
  57169. * Creates a polyhedron mesh.
  57170. *
  57171. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  57172. * 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
  57173. * to choose the wanted type.
  57174. * The parameter `size` (positive float, default 1) sets the polygon size.
  57175. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  57176. * 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`.
  57177. * 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
  57178. * 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)`).
  57179. * 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
  57180. * 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.
  57181. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57182. * 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).
  57183. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57184. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57185. */
  57186. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  57187. var polyhedron = new BABYLON.Mesh(name, scene);
  57188. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57189. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  57190. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  57191. vertexData.applyToMesh(polyhedron, options.updatable);
  57192. return polyhedron;
  57193. };
  57194. /**
  57195. * Creates a decal mesh.
  57196. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  57197. * 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.
  57198. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  57199. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  57200. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  57201. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  57202. */
  57203. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  57204. var indices = sourceMesh.getIndices();
  57205. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57206. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57207. var position = options.position || BABYLON.Vector3.Zero();
  57208. var normal = options.normal || BABYLON.Vector3.Up();
  57209. var size = options.size || BABYLON.Vector3.One();
  57210. var angle = options.angle || 0;
  57211. // Getting correct rotation
  57212. if (!normal) {
  57213. var target = new BABYLON.Vector3(0, 0, 1);
  57214. var camera = sourceMesh.getScene().activeCamera;
  57215. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  57216. normal = camera.globalPosition.subtract(cameraWorldTarget);
  57217. }
  57218. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  57219. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  57220. var pitch = Math.atan2(normal.y, len);
  57221. // Matrix
  57222. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  57223. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  57224. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  57225. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  57226. var vertexData = new BABYLON.VertexData();
  57227. vertexData.indices = [];
  57228. vertexData.positions = [];
  57229. vertexData.normals = [];
  57230. vertexData.uvs = [];
  57231. var currentVertexDataIndex = 0;
  57232. var extractDecalVector3 = function (indexId) {
  57233. var result = new BABYLON.PositionNormalVertex();
  57234. if (!indices || !positions || !normals) {
  57235. return result;
  57236. }
  57237. var vertexId = indices[indexId];
  57238. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  57239. // Send vector to decal local world
  57240. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  57241. // Get normal
  57242. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  57243. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  57244. return result;
  57245. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  57246. var clip = function (vertices, axis) {
  57247. if (vertices.length === 0) {
  57248. return vertices;
  57249. }
  57250. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  57251. var clipVertices = function (v0, v1) {
  57252. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  57253. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  57254. };
  57255. var result = new Array();
  57256. for (var index = 0; index < vertices.length; index += 3) {
  57257. var v1Out;
  57258. var v2Out;
  57259. var v3Out;
  57260. var total = 0;
  57261. var nV1 = null;
  57262. var nV2 = null;
  57263. var nV3 = null;
  57264. var nV4 = null;
  57265. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  57266. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  57267. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  57268. v1Out = d1 > 0;
  57269. v2Out = d2 > 0;
  57270. v3Out = d3 > 0;
  57271. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  57272. switch (total) {
  57273. case 0:
  57274. result.push(vertices[index]);
  57275. result.push(vertices[index + 1]);
  57276. result.push(vertices[index + 2]);
  57277. break;
  57278. case 1:
  57279. if (v1Out) {
  57280. nV1 = vertices[index + 1];
  57281. nV2 = vertices[index + 2];
  57282. nV3 = clipVertices(vertices[index], nV1);
  57283. nV4 = clipVertices(vertices[index], nV2);
  57284. }
  57285. if (v2Out) {
  57286. nV1 = vertices[index];
  57287. nV2 = vertices[index + 2];
  57288. nV3 = clipVertices(vertices[index + 1], nV1);
  57289. nV4 = clipVertices(vertices[index + 1], nV2);
  57290. result.push(nV3);
  57291. result.push(nV2.clone());
  57292. result.push(nV1.clone());
  57293. result.push(nV2.clone());
  57294. result.push(nV3.clone());
  57295. result.push(nV4);
  57296. break;
  57297. }
  57298. if (v3Out) {
  57299. nV1 = vertices[index];
  57300. nV2 = vertices[index + 1];
  57301. nV3 = clipVertices(vertices[index + 2], nV1);
  57302. nV4 = clipVertices(vertices[index + 2], nV2);
  57303. }
  57304. if (nV1 && nV2 && nV3 && nV4) {
  57305. result.push(nV1.clone());
  57306. result.push(nV2.clone());
  57307. result.push(nV3);
  57308. result.push(nV4);
  57309. result.push(nV3.clone());
  57310. result.push(nV2.clone());
  57311. }
  57312. break;
  57313. case 2:
  57314. if (!v1Out) {
  57315. nV1 = vertices[index].clone();
  57316. nV2 = clipVertices(nV1, vertices[index + 1]);
  57317. nV3 = clipVertices(nV1, vertices[index + 2]);
  57318. result.push(nV1);
  57319. result.push(nV2);
  57320. result.push(nV3);
  57321. }
  57322. if (!v2Out) {
  57323. nV1 = vertices[index + 1].clone();
  57324. nV2 = clipVertices(nV1, vertices[index + 2]);
  57325. nV3 = clipVertices(nV1, vertices[index]);
  57326. result.push(nV1);
  57327. result.push(nV2);
  57328. result.push(nV3);
  57329. }
  57330. if (!v3Out) {
  57331. nV1 = vertices[index + 2].clone();
  57332. nV2 = clipVertices(nV1, vertices[index]);
  57333. nV3 = clipVertices(nV1, vertices[index + 1]);
  57334. result.push(nV1);
  57335. result.push(nV2);
  57336. result.push(nV3);
  57337. }
  57338. break;
  57339. case 3:
  57340. break;
  57341. }
  57342. }
  57343. return result;
  57344. };
  57345. for (var index = 0; index < indices.length; index += 3) {
  57346. var faceVertices = new Array();
  57347. faceVertices.push(extractDecalVector3(index));
  57348. faceVertices.push(extractDecalVector3(index + 1));
  57349. faceVertices.push(extractDecalVector3(index + 2));
  57350. // Clip
  57351. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  57352. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  57353. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  57354. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  57355. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  57356. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  57357. if (faceVertices.length === 0) {
  57358. continue;
  57359. }
  57360. // Add UVs and get back to world
  57361. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  57362. var vertex = faceVertices[vIndex];
  57363. //TODO check for Int32Array | Uint32Array | Uint16Array
  57364. vertexData.indices.push(currentVertexDataIndex);
  57365. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  57366. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  57367. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  57368. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  57369. currentVertexDataIndex++;
  57370. }
  57371. }
  57372. // Return mesh
  57373. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  57374. vertexData.applyToMesh(decal);
  57375. decal.position = position.clone();
  57376. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  57377. return decal;
  57378. };
  57379. // Privates
  57380. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  57381. // extrusion geometry
  57382. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  57383. var tangents = path3D.getTangents();
  57384. var normals = path3D.getNormals();
  57385. var binormals = path3D.getBinormals();
  57386. var distances = path3D.getDistances();
  57387. var angle = 0;
  57388. var returnScale = function () { return scale !== null ? scale : 1; };
  57389. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  57390. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  57391. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  57392. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57393. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57394. for (var i = 0; i < curve.length; i++) {
  57395. var shapePath = new Array();
  57396. var angleStep = rotate(i, distances[i]);
  57397. var scaleRatio = scl(i, distances[i]);
  57398. for (var p = 0; p < shape.length; p++) {
  57399. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  57400. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  57401. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  57402. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  57403. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  57404. shapePath[p] = rotated;
  57405. }
  57406. shapePaths[index] = shapePath;
  57407. angle += angleStep;
  57408. index++;
  57409. }
  57410. // cap
  57411. var capPath = function (shapePath) {
  57412. var pointCap = Array();
  57413. var barycenter = BABYLON.Vector3.Zero();
  57414. var i;
  57415. for (i = 0; i < shapePath.length; i++) {
  57416. barycenter.addInPlace(shapePath[i]);
  57417. }
  57418. barycenter.scaleInPlace(1.0 / shapePath.length);
  57419. for (i = 0; i < shapePath.length; i++) {
  57420. pointCap.push(barycenter);
  57421. }
  57422. return pointCap;
  57423. };
  57424. switch (cap) {
  57425. case BABYLON.Mesh.NO_CAP:
  57426. break;
  57427. case BABYLON.Mesh.CAP_START:
  57428. shapePaths[0] = capPath(shapePaths[2]);
  57429. shapePaths[1] = shapePaths[2];
  57430. break;
  57431. case BABYLON.Mesh.CAP_END:
  57432. shapePaths[index] = shapePaths[index - 1];
  57433. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57434. break;
  57435. case BABYLON.Mesh.CAP_ALL:
  57436. shapePaths[0] = capPath(shapePaths[2]);
  57437. shapePaths[1] = shapePaths[2];
  57438. shapePaths[index] = shapePaths[index - 1];
  57439. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57440. break;
  57441. default:
  57442. break;
  57443. }
  57444. return shapePaths;
  57445. };
  57446. var path3D;
  57447. var pathArray;
  57448. if (instance) {
  57449. path3D = (instance.path3D).update(curve);
  57450. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  57451. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  57452. return instance;
  57453. }
  57454. // extruded shape creation
  57455. path3D = new BABYLON.Path3D(curve);
  57456. var newShapePaths = new Array();
  57457. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57458. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  57459. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  57460. extrudedGeneric.pathArray = pathArray;
  57461. extrudedGeneric.path3D = path3D;
  57462. extrudedGeneric.cap = cap;
  57463. return extrudedGeneric;
  57464. };
  57465. return MeshBuilder;
  57466. }());
  57467. BABYLON.MeshBuilder = MeshBuilder;
  57468. })(BABYLON || (BABYLON = {}));
  57469. //# sourceMappingURL=babylon.meshBuilder.js.map
  57470. "use strict";
  57471. var BABYLON;
  57472. (function (BABYLON) {
  57473. /**
  57474. * Draco compression (https://google.github.io/draco/)
  57475. */
  57476. var DracoCompression = /** @class */ (function () {
  57477. /**
  57478. * Constructor
  57479. * @param numWorkers The number of workers for async operations
  57480. */
  57481. function DracoCompression(numWorkers) {
  57482. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  57483. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  57484. if (!workerBlobUrl || !Worker) {
  57485. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  57486. return;
  57487. }
  57488. var workers = new Array(numWorkers);
  57489. for (var i = 0; i < workers.length; i++) {
  57490. var worker = new Worker(workerBlobUrl);
  57491. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  57492. workers[i] = worker;
  57493. }
  57494. this._workerPool = new BABYLON.WorkerPool(workers);
  57495. }
  57496. /**
  57497. * Stop all async operations and release resources.
  57498. */
  57499. DracoCompression.prototype.dispose = function () {
  57500. this._workerPool.dispose();
  57501. delete this._workerPool;
  57502. };
  57503. /**
  57504. * Decode Draco compressed mesh data to vertex data.
  57505. * @param data The array buffer view for the Draco compression data
  57506. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  57507. * @returns A promise that resolves with the decoded vertex data
  57508. */
  57509. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  57510. var _this = this;
  57511. return new Promise(function (resolve, reject) {
  57512. _this._workerPool.push(function (worker, onComplete) {
  57513. var vertexData = new BABYLON.VertexData();
  57514. var onError = function (error) {
  57515. worker.removeEventListener("error", onError);
  57516. worker.removeEventListener("message", onMessage);
  57517. reject(error);
  57518. onComplete();
  57519. };
  57520. var onMessage = function (message) {
  57521. if (message.data === "done") {
  57522. worker.removeEventListener("error", onError);
  57523. worker.removeEventListener("message", onMessage);
  57524. resolve(vertexData);
  57525. onComplete();
  57526. }
  57527. else if (message.data.id === "indices") {
  57528. vertexData.indices = message.data.value;
  57529. }
  57530. else {
  57531. vertexData.set(message.data.value, message.data.id);
  57532. }
  57533. };
  57534. worker.addEventListener("error", onError);
  57535. worker.addEventListener("message", onMessage);
  57536. var dataCopy = new Uint8Array(data.byteLength);
  57537. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  57538. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  57539. });
  57540. });
  57541. };
  57542. /**
  57543. * The worker function that gets converted to a blob url to pass into a worker.
  57544. */
  57545. DracoCompression._Worker = function () {
  57546. // self is actually a DedicatedWorkerGlobalScope
  57547. var _self = self;
  57548. var decodeMesh = function (data, attributes) {
  57549. var dracoModule = new DracoDecoderModule();
  57550. var buffer = new dracoModule.DecoderBuffer();
  57551. buffer.Init(data, data.byteLength);
  57552. var decoder = new dracoModule.Decoder();
  57553. var geometry;
  57554. var status;
  57555. try {
  57556. var type = decoder.GetEncodedGeometryType(buffer);
  57557. switch (type) {
  57558. case dracoModule.TRIANGULAR_MESH:
  57559. geometry = new dracoModule.Mesh();
  57560. status = decoder.DecodeBufferToMesh(buffer, geometry);
  57561. break;
  57562. case dracoModule.POINT_CLOUD:
  57563. geometry = new dracoModule.PointCloud();
  57564. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  57565. break;
  57566. default:
  57567. throw new Error("Invalid geometry type " + type);
  57568. }
  57569. if (!status.ok() || !geometry.ptr) {
  57570. throw new Error(status.error_msg());
  57571. }
  57572. var numPoints = geometry.num_points();
  57573. if (type === dracoModule.TRIANGULAR_MESH) {
  57574. var numFaces = geometry.num_faces();
  57575. var faceIndices = new dracoModule.DracoInt32Array();
  57576. try {
  57577. var indices = new Uint32Array(numFaces * 3);
  57578. for (var i = 0; i < numFaces; i++) {
  57579. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  57580. var offset = i * 3;
  57581. indices[offset + 0] = faceIndices.GetValue(0);
  57582. indices[offset + 1] = faceIndices.GetValue(1);
  57583. indices[offset + 2] = faceIndices.GetValue(2);
  57584. }
  57585. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  57586. }
  57587. finally {
  57588. dracoModule.destroy(faceIndices);
  57589. }
  57590. }
  57591. for (var kind in attributes) {
  57592. var uniqueId = attributes[kind];
  57593. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  57594. var dracoData = new dracoModule.DracoFloat32Array();
  57595. try {
  57596. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  57597. var babylonData = new Float32Array(numPoints * attribute.num_components());
  57598. for (var i = 0; i < babylonData.length; i++) {
  57599. babylonData[i] = dracoData.GetValue(i);
  57600. }
  57601. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  57602. }
  57603. finally {
  57604. dracoModule.destroy(dracoData);
  57605. }
  57606. }
  57607. }
  57608. finally {
  57609. if (geometry) {
  57610. dracoModule.destroy(geometry);
  57611. }
  57612. dracoModule.destroy(decoder);
  57613. dracoModule.destroy(buffer);
  57614. }
  57615. _self.postMessage("done");
  57616. };
  57617. _self.onmessage = function (event) {
  57618. switch (event.data.id) {
  57619. case "initDecoder": {
  57620. importScripts(event.data.url);
  57621. break;
  57622. }
  57623. case "decodeMesh": {
  57624. decodeMesh(event.data.data, event.data.attributes);
  57625. break;
  57626. }
  57627. }
  57628. };
  57629. };
  57630. DracoCompression._GetDefaultDecoderUrl = function () {
  57631. if (!BABYLON.Tools.IsWindowObjectExist) {
  57632. return null;
  57633. }
  57634. for (var i = 0; i < document.scripts.length; i++) {
  57635. if (document.scripts[i].type === "text/x-draco-decoder") {
  57636. return document.scripts[i].src;
  57637. }
  57638. }
  57639. return null;
  57640. };
  57641. /**
  57642. * Gets the url to the draco decoder if available.
  57643. */
  57644. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  57645. return DracoCompression;
  57646. }());
  57647. BABYLON.DracoCompression = DracoCompression;
  57648. })(BABYLON || (BABYLON = {}));
  57649. //# sourceMappingURL=babylon.dracoCompression.js.map
  57650. "use strict";
  57651. var BABYLON;
  57652. (function (BABYLON) {
  57653. var AudioEngine = /** @class */ (function () {
  57654. function AudioEngine() {
  57655. this._audioContext = null;
  57656. this._audioContextInitialized = false;
  57657. this.canUseWebAudio = false;
  57658. this.WarnedWebAudioUnsupported = false;
  57659. this.unlocked = false;
  57660. this.isMP3supported = false;
  57661. this.isOGGsupported = false;
  57662. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  57663. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  57664. this.canUseWebAudio = true;
  57665. }
  57666. var audioElem = document.createElement('audio');
  57667. try {
  57668. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  57669. this.isMP3supported = true;
  57670. }
  57671. }
  57672. catch (e) {
  57673. // protect error during capability check.
  57674. }
  57675. try {
  57676. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  57677. this.isOGGsupported = true;
  57678. }
  57679. }
  57680. catch (e) {
  57681. // protect error during capability check.
  57682. }
  57683. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  57684. this._unlockiOSaudio();
  57685. }
  57686. else {
  57687. this.unlocked = true;
  57688. }
  57689. }
  57690. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  57691. get: function () {
  57692. if (!this._audioContextInitialized) {
  57693. this._initializeAudioContext();
  57694. }
  57695. return this._audioContext;
  57696. },
  57697. enumerable: true,
  57698. configurable: true
  57699. });
  57700. AudioEngine.prototype._unlockiOSaudio = function () {
  57701. var _this = this;
  57702. var unlockaudio = function () {
  57703. if (!_this.audioContext) {
  57704. return;
  57705. }
  57706. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  57707. var source = _this.audioContext.createBufferSource();
  57708. source.buffer = buffer;
  57709. source.connect(_this.audioContext.destination);
  57710. source.start(0);
  57711. setTimeout(function () {
  57712. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  57713. _this.unlocked = true;
  57714. window.removeEventListener('touchend', unlockaudio, false);
  57715. if (_this.onAudioUnlocked) {
  57716. _this.onAudioUnlocked();
  57717. }
  57718. }
  57719. }, 0);
  57720. };
  57721. window.addEventListener('touchend', unlockaudio, false);
  57722. };
  57723. AudioEngine.prototype._initializeAudioContext = function () {
  57724. try {
  57725. if (this.canUseWebAudio) {
  57726. this._audioContext = new AudioContext();
  57727. // create a global volume gain node
  57728. this.masterGain = this._audioContext.createGain();
  57729. this.masterGain.gain.value = 1;
  57730. this.masterGain.connect(this._audioContext.destination);
  57731. this._audioContextInitialized = true;
  57732. }
  57733. }
  57734. catch (e) {
  57735. this.canUseWebAudio = false;
  57736. BABYLON.Tools.Error("Web Audio: " + e.message);
  57737. }
  57738. };
  57739. AudioEngine.prototype.dispose = function () {
  57740. if (this.canUseWebAudio && this._audioContextInitialized) {
  57741. if (this._connectedAnalyser && this._audioContext) {
  57742. this._connectedAnalyser.stopDebugCanvas();
  57743. this._connectedAnalyser.dispose();
  57744. this.masterGain.disconnect();
  57745. this.masterGain.connect(this._audioContext.destination);
  57746. this._connectedAnalyser = null;
  57747. }
  57748. this.masterGain.gain.value = 1;
  57749. }
  57750. this.WarnedWebAudioUnsupported = false;
  57751. };
  57752. AudioEngine.prototype.getGlobalVolume = function () {
  57753. if (this.canUseWebAudio && this._audioContextInitialized) {
  57754. return this.masterGain.gain.value;
  57755. }
  57756. else {
  57757. return -1;
  57758. }
  57759. };
  57760. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  57761. if (this.canUseWebAudio && this._audioContextInitialized) {
  57762. this.masterGain.gain.value = newVolume;
  57763. }
  57764. };
  57765. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  57766. if (this._connectedAnalyser) {
  57767. this._connectedAnalyser.stopDebugCanvas();
  57768. }
  57769. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  57770. this._connectedAnalyser = analyser;
  57771. this.masterGain.disconnect();
  57772. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  57773. }
  57774. };
  57775. return AudioEngine;
  57776. }());
  57777. BABYLON.AudioEngine = AudioEngine;
  57778. })(BABYLON || (BABYLON = {}));
  57779. //# sourceMappingURL=babylon.audioEngine.js.map
  57780. "use strict";
  57781. var BABYLON;
  57782. (function (BABYLON) {
  57783. var Sound = /** @class */ (function () {
  57784. /**
  57785. * Create a sound and attach it to a scene
  57786. * @param name Name of your sound
  57787. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  57788. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  57789. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  57790. */
  57791. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  57792. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  57793. var _this = this;
  57794. this.autoplay = false;
  57795. this.loop = false;
  57796. this.useCustomAttenuation = false;
  57797. this.spatialSound = false;
  57798. this.refDistance = 1;
  57799. this.rolloffFactor = 1;
  57800. this.maxDistance = 100;
  57801. this.distanceModel = "linear";
  57802. this._panningModel = "equalpower";
  57803. this._playbackRate = 1;
  57804. this._streaming = false;
  57805. this._startTime = 0;
  57806. this._startOffset = 0;
  57807. this._position = BABYLON.Vector3.Zero();
  57808. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  57809. this._volume = 1;
  57810. this._isReadyToPlay = false;
  57811. this.isPlaying = false;
  57812. this.isPaused = false;
  57813. this._isDirectional = false;
  57814. // Used if you'd like to create a directional sound.
  57815. // If not set, the sound will be omnidirectional
  57816. this._coneInnerAngle = 360;
  57817. this._coneOuterAngle = 360;
  57818. this._coneOuterGain = 0;
  57819. this._isOutputConnected = false;
  57820. this._urlType = "Unknown";
  57821. this.name = name;
  57822. this._scene = scene;
  57823. this._readyToPlayCallback = readyToPlayCallback;
  57824. // Default custom attenuation function is a linear attenuation
  57825. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  57826. if (currentDistance < maxDistance) {
  57827. return currentVolume * (1 - currentDistance / maxDistance);
  57828. }
  57829. else {
  57830. return 0;
  57831. }
  57832. };
  57833. if (options) {
  57834. this.autoplay = options.autoplay || false;
  57835. this.loop = options.loop || false;
  57836. // if volume === 0, we need another way to check this option
  57837. if (options.volume !== undefined) {
  57838. this._volume = options.volume;
  57839. }
  57840. this.spatialSound = options.spatialSound || false;
  57841. this.maxDistance = options.maxDistance || 100;
  57842. this.useCustomAttenuation = options.useCustomAttenuation || false;
  57843. this.rolloffFactor = options.rolloffFactor || 1;
  57844. this.refDistance = options.refDistance || 1;
  57845. this.distanceModel = options.distanceModel || "linear";
  57846. this._playbackRate = options.playbackRate || 1;
  57847. this._streaming = options.streaming || false;
  57848. }
  57849. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57850. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  57851. this._soundGain.gain.value = this._volume;
  57852. this._inputAudioNode = this._soundGain;
  57853. this._ouputAudioNode = this._soundGain;
  57854. if (this.spatialSound) {
  57855. this._createSpatialParameters();
  57856. }
  57857. this._scene.mainSoundTrack.AddSound(this);
  57858. var validParameter = true;
  57859. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  57860. if (urlOrArrayBuffer) {
  57861. if (typeof (urlOrArrayBuffer) === "string")
  57862. this._urlType = "String";
  57863. if (Array.isArray(urlOrArrayBuffer))
  57864. this._urlType = "Array";
  57865. if (urlOrArrayBuffer instanceof ArrayBuffer)
  57866. this._urlType = "ArrayBuffer";
  57867. var urls = [];
  57868. var codecSupportedFound = false;
  57869. switch (this._urlType) {
  57870. case "ArrayBuffer":
  57871. if (urlOrArrayBuffer.byteLength > 0) {
  57872. codecSupportedFound = true;
  57873. this._soundLoaded(urlOrArrayBuffer);
  57874. }
  57875. break;
  57876. case "String":
  57877. urls.push(urlOrArrayBuffer);
  57878. case "Array":
  57879. if (urls.length === 0)
  57880. urls = urlOrArrayBuffer;
  57881. // If we found a supported format, we load it immediately and stop the loop
  57882. for (var i = 0; i < urls.length; i++) {
  57883. var url = urls[i];
  57884. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  57885. codecSupportedFound = true;
  57886. }
  57887. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  57888. codecSupportedFound = true;
  57889. }
  57890. if (url.indexOf(".wav", url.length - 4) !== -1) {
  57891. codecSupportedFound = true;
  57892. }
  57893. if (url.indexOf("blob:") !== -1) {
  57894. codecSupportedFound = true;
  57895. }
  57896. if (codecSupportedFound) {
  57897. // Loading sound using XHR2
  57898. if (!this._streaming) {
  57899. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  57900. }
  57901. else {
  57902. this._htmlAudioElement = new Audio(url);
  57903. this._htmlAudioElement.controls = false;
  57904. this._htmlAudioElement.loop = this.loop;
  57905. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  57906. this._htmlAudioElement.preload = "auto";
  57907. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  57908. _this._isReadyToPlay = true;
  57909. if (_this.autoplay) {
  57910. _this.play();
  57911. }
  57912. if (_this._readyToPlayCallback) {
  57913. _this._readyToPlayCallback();
  57914. }
  57915. });
  57916. document.body.appendChild(this._htmlAudioElement);
  57917. }
  57918. break;
  57919. }
  57920. }
  57921. break;
  57922. default:
  57923. validParameter = false;
  57924. break;
  57925. }
  57926. if (!validParameter) {
  57927. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  57928. }
  57929. else {
  57930. if (!codecSupportedFound) {
  57931. this._isReadyToPlay = true;
  57932. // Simulating a ready to play event to avoid breaking code path
  57933. if (this._readyToPlayCallback) {
  57934. window.setTimeout(function () {
  57935. if (_this._readyToPlayCallback) {
  57936. _this._readyToPlayCallback();
  57937. }
  57938. }, 1000);
  57939. }
  57940. }
  57941. }
  57942. }
  57943. }
  57944. else {
  57945. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  57946. this._scene.mainSoundTrack.AddSound(this);
  57947. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  57948. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  57949. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  57950. }
  57951. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  57952. if (this._readyToPlayCallback) {
  57953. window.setTimeout(function () {
  57954. if (_this._readyToPlayCallback) {
  57955. _this._readyToPlayCallback();
  57956. }
  57957. }, 1000);
  57958. }
  57959. }
  57960. }
  57961. Sound.prototype.dispose = function () {
  57962. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  57963. if (this.isPlaying) {
  57964. this.stop();
  57965. }
  57966. this._isReadyToPlay = false;
  57967. if (this.soundTrackId === -1) {
  57968. this._scene.mainSoundTrack.RemoveSound(this);
  57969. }
  57970. else {
  57971. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  57972. }
  57973. if (this._soundGain) {
  57974. this._soundGain.disconnect();
  57975. this._soundGain = null;
  57976. }
  57977. if (this._soundPanner) {
  57978. this._soundPanner.disconnect();
  57979. this._soundPanner = null;
  57980. }
  57981. if (this._soundSource) {
  57982. this._soundSource.disconnect();
  57983. this._soundSource = null;
  57984. }
  57985. this._audioBuffer = null;
  57986. if (this._htmlAudioElement) {
  57987. this._htmlAudioElement.pause();
  57988. this._htmlAudioElement.src = "";
  57989. document.body.removeChild(this._htmlAudioElement);
  57990. }
  57991. if (this._connectedMesh && this._registerFunc) {
  57992. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57993. this._connectedMesh = null;
  57994. }
  57995. }
  57996. };
  57997. Sound.prototype.isReady = function () {
  57998. return this._isReadyToPlay;
  57999. };
  58000. Sound.prototype._soundLoaded = function (audioData) {
  58001. var _this = this;
  58002. if (!BABYLON.Engine.audioEngine.audioContext) {
  58003. return;
  58004. }
  58005. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  58006. _this._audioBuffer = buffer;
  58007. _this._isReadyToPlay = true;
  58008. if (_this.autoplay) {
  58009. _this.play();
  58010. }
  58011. if (_this._readyToPlayCallback) {
  58012. _this._readyToPlayCallback();
  58013. }
  58014. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  58015. };
  58016. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  58017. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58018. this._audioBuffer = audioBuffer;
  58019. this._isReadyToPlay = true;
  58020. }
  58021. };
  58022. Sound.prototype.updateOptions = function (options) {
  58023. if (options) {
  58024. this.loop = options.loop || this.loop;
  58025. this.maxDistance = options.maxDistance || this.maxDistance;
  58026. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  58027. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  58028. this.refDistance = options.refDistance || this.refDistance;
  58029. this.distanceModel = options.distanceModel || this.distanceModel;
  58030. this._playbackRate = options.playbackRate || this._playbackRate;
  58031. this._updateSpatialParameters();
  58032. if (this.isPlaying) {
  58033. if (this._streaming) {
  58034. this._htmlAudioElement.playbackRate = this._playbackRate;
  58035. }
  58036. else {
  58037. if (this._soundSource) {
  58038. this._soundSource.playbackRate.value = this._playbackRate;
  58039. }
  58040. }
  58041. }
  58042. }
  58043. };
  58044. Sound.prototype._createSpatialParameters = function () {
  58045. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58046. if (this._scene.headphone) {
  58047. this._panningModel = "HRTF";
  58048. }
  58049. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  58050. this._updateSpatialParameters();
  58051. this._soundPanner.connect(this._ouputAudioNode);
  58052. this._inputAudioNode = this._soundPanner;
  58053. }
  58054. };
  58055. Sound.prototype._updateSpatialParameters = function () {
  58056. if (this.spatialSound && this._soundPanner) {
  58057. if (this.useCustomAttenuation) {
  58058. // Tricks to disable in a way embedded Web Audio attenuation
  58059. this._soundPanner.distanceModel = "linear";
  58060. this._soundPanner.maxDistance = Number.MAX_VALUE;
  58061. this._soundPanner.refDistance = 1;
  58062. this._soundPanner.rolloffFactor = 1;
  58063. this._soundPanner.panningModel = this._panningModel;
  58064. }
  58065. else {
  58066. this._soundPanner.distanceModel = this.distanceModel;
  58067. this._soundPanner.maxDistance = this.maxDistance;
  58068. this._soundPanner.refDistance = this.refDistance;
  58069. this._soundPanner.rolloffFactor = this.rolloffFactor;
  58070. this._soundPanner.panningModel = this._panningModel;
  58071. }
  58072. }
  58073. };
  58074. Sound.prototype.switchPanningModelToHRTF = function () {
  58075. this._panningModel = "HRTF";
  58076. this._switchPanningModel();
  58077. };
  58078. Sound.prototype.switchPanningModelToEqualPower = function () {
  58079. this._panningModel = "equalpower";
  58080. this._switchPanningModel();
  58081. };
  58082. Sound.prototype._switchPanningModel = function () {
  58083. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58084. this._soundPanner.panningModel = this._panningModel;
  58085. }
  58086. };
  58087. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  58088. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58089. if (this._isOutputConnected) {
  58090. this._ouputAudioNode.disconnect();
  58091. }
  58092. this._ouputAudioNode.connect(soundTrackAudioNode);
  58093. this._isOutputConnected = true;
  58094. }
  58095. };
  58096. /**
  58097. * Transform this sound into a directional source
  58098. * @param coneInnerAngle Size of the inner cone in degree
  58099. * @param coneOuterAngle Size of the outer cone in degree
  58100. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  58101. */
  58102. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  58103. if (coneOuterAngle < coneInnerAngle) {
  58104. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  58105. return;
  58106. }
  58107. this._coneInnerAngle = coneInnerAngle;
  58108. this._coneOuterAngle = coneOuterAngle;
  58109. this._coneOuterGain = coneOuterGain;
  58110. this._isDirectional = true;
  58111. if (this.isPlaying && this.loop) {
  58112. this.stop();
  58113. this.play();
  58114. }
  58115. };
  58116. Sound.prototype.setPosition = function (newPosition) {
  58117. this._position = newPosition;
  58118. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58119. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58120. }
  58121. };
  58122. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  58123. this._localDirection = newLocalDirection;
  58124. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  58125. this._updateDirection();
  58126. }
  58127. };
  58128. Sound.prototype._updateDirection = function () {
  58129. if (!this._connectedMesh || !this._soundPanner) {
  58130. return;
  58131. }
  58132. var mat = this._connectedMesh.getWorldMatrix();
  58133. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  58134. direction.normalize();
  58135. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  58136. };
  58137. Sound.prototype.updateDistanceFromListener = function () {
  58138. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  58139. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  58140. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  58141. }
  58142. };
  58143. Sound.prototype.setAttenuationFunction = function (callback) {
  58144. this._customAttenuationFunction = callback;
  58145. };
  58146. /**
  58147. * Play the sound
  58148. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  58149. * @param offset (optional) Start the sound setting it at a specific time
  58150. */
  58151. Sound.prototype.play = function (time, offset) {
  58152. var _this = this;
  58153. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  58154. try {
  58155. if (this._startOffset < 0) {
  58156. time = -this._startOffset;
  58157. this._startOffset = 0;
  58158. }
  58159. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58160. if (!this._soundSource || !this._streamingSource) {
  58161. if (this.spatialSound && this._soundPanner) {
  58162. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58163. if (this._isDirectional) {
  58164. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  58165. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  58166. this._soundPanner.coneOuterGain = this._coneOuterGain;
  58167. if (this._connectedMesh) {
  58168. this._updateDirection();
  58169. }
  58170. else {
  58171. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  58172. }
  58173. }
  58174. }
  58175. }
  58176. if (this._streaming) {
  58177. if (!this._streamingSource) {
  58178. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  58179. this._htmlAudioElement.onended = function () { _this._onended(); };
  58180. this._htmlAudioElement.playbackRate = this._playbackRate;
  58181. }
  58182. this._streamingSource.disconnect();
  58183. this._streamingSource.connect(this._inputAudioNode);
  58184. this._htmlAudioElement.play();
  58185. }
  58186. else {
  58187. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  58188. this._soundSource.buffer = this._audioBuffer;
  58189. this._soundSource.connect(this._inputAudioNode);
  58190. this._soundSource.loop = this.loop;
  58191. this._soundSource.playbackRate.value = this._playbackRate;
  58192. this._soundSource.onended = function () { _this._onended(); };
  58193. if (this._soundSource.buffer) {
  58194. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  58195. }
  58196. }
  58197. this._startTime = startTime;
  58198. this.isPlaying = true;
  58199. this.isPaused = false;
  58200. }
  58201. catch (ex) {
  58202. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  58203. }
  58204. }
  58205. };
  58206. Sound.prototype._onended = function () {
  58207. this.isPlaying = false;
  58208. if (this.onended) {
  58209. this.onended();
  58210. }
  58211. };
  58212. /**
  58213. * Stop the sound
  58214. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  58215. */
  58216. Sound.prototype.stop = function (time) {
  58217. if (this.isPlaying) {
  58218. if (this._streaming) {
  58219. this._htmlAudioElement.pause();
  58220. // Test needed for Firefox or it will generate an Invalid State Error
  58221. if (this._htmlAudioElement.currentTime > 0) {
  58222. this._htmlAudioElement.currentTime = 0;
  58223. }
  58224. }
  58225. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  58226. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58227. this._soundSource.stop(stopTime);
  58228. this._soundSource.onended = function () { };
  58229. if (!this.isPaused) {
  58230. this._startOffset = 0;
  58231. }
  58232. }
  58233. this.isPlaying = false;
  58234. }
  58235. };
  58236. Sound.prototype.pause = function () {
  58237. if (this.isPlaying) {
  58238. this.isPaused = true;
  58239. if (this._streaming) {
  58240. this._htmlAudioElement.pause();
  58241. }
  58242. else if (BABYLON.Engine.audioEngine.audioContext) {
  58243. this.stop(0);
  58244. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  58245. }
  58246. }
  58247. };
  58248. Sound.prototype.setVolume = function (newVolume, time) {
  58249. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  58250. if (time && BABYLON.Engine.audioEngine.audioContext) {
  58251. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  58252. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  58253. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  58254. }
  58255. else {
  58256. this._soundGain.gain.value = newVolume;
  58257. }
  58258. }
  58259. this._volume = newVolume;
  58260. };
  58261. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  58262. this._playbackRate = newPlaybackRate;
  58263. if (this.isPlaying) {
  58264. if (this._streaming) {
  58265. this._htmlAudioElement.playbackRate = this._playbackRate;
  58266. }
  58267. else if (this._soundSource) {
  58268. this._soundSource.playbackRate.value = this._playbackRate;
  58269. }
  58270. }
  58271. };
  58272. Sound.prototype.getVolume = function () {
  58273. return this._volume;
  58274. };
  58275. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  58276. var _this = this;
  58277. if (this._connectedMesh && this._registerFunc) {
  58278. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58279. this._registerFunc = null;
  58280. }
  58281. this._connectedMesh = meshToConnectTo;
  58282. if (!this.spatialSound) {
  58283. this.spatialSound = true;
  58284. this._createSpatialParameters();
  58285. if (this.isPlaying && this.loop) {
  58286. this.stop();
  58287. this.play();
  58288. }
  58289. }
  58290. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  58291. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  58292. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  58293. };
  58294. Sound.prototype.detachFromMesh = function () {
  58295. if (this._connectedMesh && this._registerFunc) {
  58296. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58297. this._registerFunc = null;
  58298. this._connectedMesh = null;
  58299. }
  58300. };
  58301. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  58302. if (!node.getBoundingInfo) {
  58303. return;
  58304. }
  58305. var mesh = node;
  58306. var boundingInfo = mesh.getBoundingInfo();
  58307. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  58308. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  58309. this._updateDirection();
  58310. }
  58311. };
  58312. Sound.prototype.clone = function () {
  58313. var _this = this;
  58314. if (!this._streaming) {
  58315. var setBufferAndRun = function () {
  58316. if (_this._isReadyToPlay) {
  58317. clonedSound._audioBuffer = _this.getAudioBuffer();
  58318. clonedSound._isReadyToPlay = true;
  58319. if (clonedSound.autoplay) {
  58320. clonedSound.play();
  58321. }
  58322. }
  58323. else {
  58324. window.setTimeout(setBufferAndRun, 300);
  58325. }
  58326. };
  58327. var currentOptions = {
  58328. autoplay: this.autoplay, loop: this.loop,
  58329. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  58330. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  58331. refDistance: this.refDistance, distanceModel: this.distanceModel
  58332. };
  58333. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  58334. if (this.useCustomAttenuation) {
  58335. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  58336. }
  58337. clonedSound.setPosition(this._position);
  58338. clonedSound.setPlaybackRate(this._playbackRate);
  58339. setBufferAndRun();
  58340. return clonedSound;
  58341. }
  58342. else {
  58343. return null;
  58344. }
  58345. };
  58346. Sound.prototype.getAudioBuffer = function () {
  58347. return this._audioBuffer;
  58348. };
  58349. Sound.prototype.serialize = function () {
  58350. var serializationObject = {
  58351. name: this.name,
  58352. url: this.name,
  58353. autoplay: this.autoplay,
  58354. loop: this.loop,
  58355. volume: this._volume,
  58356. spatialSound: this.spatialSound,
  58357. maxDistance: this.maxDistance,
  58358. rolloffFactor: this.rolloffFactor,
  58359. refDistance: this.refDistance,
  58360. distanceModel: this.distanceModel,
  58361. playbackRate: this._playbackRate,
  58362. panningModel: this._panningModel,
  58363. soundTrackId: this.soundTrackId
  58364. };
  58365. if (this.spatialSound) {
  58366. if (this._connectedMesh)
  58367. serializationObject.connectedMeshId = this._connectedMesh.id;
  58368. serializationObject.position = this._position.asArray();
  58369. serializationObject.refDistance = this.refDistance;
  58370. serializationObject.distanceModel = this.distanceModel;
  58371. serializationObject.isDirectional = this._isDirectional;
  58372. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  58373. serializationObject.coneInnerAngle = this._coneInnerAngle;
  58374. serializationObject.coneOuterAngle = this._coneOuterAngle;
  58375. serializationObject.coneOuterGain = this._coneOuterGain;
  58376. }
  58377. return serializationObject;
  58378. };
  58379. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  58380. var soundName = parsedSound.name;
  58381. var soundUrl;
  58382. if (parsedSound.url) {
  58383. soundUrl = rootUrl + parsedSound.url;
  58384. }
  58385. else {
  58386. soundUrl = rootUrl + soundName;
  58387. }
  58388. var options = {
  58389. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  58390. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  58391. rolloffFactor: parsedSound.rolloffFactor,
  58392. refDistance: parsedSound.refDistance,
  58393. distanceModel: parsedSound.distanceModel,
  58394. playbackRate: parsedSound.playbackRate
  58395. };
  58396. var newSound;
  58397. if (!sourceSound) {
  58398. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  58399. scene._addPendingData(newSound);
  58400. }
  58401. else {
  58402. var setBufferAndRun = function () {
  58403. if (sourceSound._isReadyToPlay) {
  58404. newSound._audioBuffer = sourceSound.getAudioBuffer();
  58405. newSound._isReadyToPlay = true;
  58406. if (newSound.autoplay) {
  58407. newSound.play();
  58408. }
  58409. }
  58410. else {
  58411. window.setTimeout(setBufferAndRun, 300);
  58412. }
  58413. };
  58414. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  58415. setBufferAndRun();
  58416. }
  58417. if (parsedSound.position) {
  58418. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  58419. newSound.setPosition(soundPosition);
  58420. }
  58421. if (parsedSound.isDirectional) {
  58422. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  58423. if (parsedSound.localDirectionToMesh) {
  58424. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  58425. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  58426. }
  58427. }
  58428. if (parsedSound.connectedMeshId) {
  58429. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  58430. if (connectedMesh) {
  58431. newSound.attachToMesh(connectedMesh);
  58432. }
  58433. }
  58434. return newSound;
  58435. };
  58436. return Sound;
  58437. }());
  58438. BABYLON.Sound = Sound;
  58439. })(BABYLON || (BABYLON = {}));
  58440. //# sourceMappingURL=babylon.sound.js.map
  58441. "use strict";
  58442. var BABYLON;
  58443. (function (BABYLON) {
  58444. var SoundTrack = /** @class */ (function () {
  58445. function SoundTrack(scene, options) {
  58446. this.id = -1;
  58447. this._isMainTrack = false;
  58448. this._isInitialized = false;
  58449. this._scene = scene;
  58450. this.soundCollection = new Array();
  58451. this._options = options;
  58452. if (!this._isMainTrack) {
  58453. this._scene.soundTracks.push(this);
  58454. this.id = this._scene.soundTracks.length - 1;
  58455. }
  58456. }
  58457. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  58458. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58459. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  58460. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  58461. if (this._options) {
  58462. if (this._options.volume) {
  58463. this._outputAudioNode.gain.value = this._options.volume;
  58464. }
  58465. if (this._options.mainTrack) {
  58466. this._isMainTrack = this._options.mainTrack;
  58467. }
  58468. }
  58469. this._isInitialized = true;
  58470. }
  58471. };
  58472. SoundTrack.prototype.dispose = function () {
  58473. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  58474. if (this._connectedAnalyser) {
  58475. this._connectedAnalyser.stopDebugCanvas();
  58476. }
  58477. while (this.soundCollection.length) {
  58478. this.soundCollection[0].dispose();
  58479. }
  58480. if (this._outputAudioNode) {
  58481. this._outputAudioNode.disconnect();
  58482. }
  58483. this._outputAudioNode = null;
  58484. }
  58485. };
  58486. SoundTrack.prototype.AddSound = function (sound) {
  58487. if (!this._isInitialized) {
  58488. this._initializeSoundTrackAudioGraph();
  58489. }
  58490. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58491. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  58492. }
  58493. if (sound.soundTrackId) {
  58494. if (sound.soundTrackId === -1) {
  58495. this._scene.mainSoundTrack.RemoveSound(sound);
  58496. }
  58497. else {
  58498. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  58499. }
  58500. }
  58501. this.soundCollection.push(sound);
  58502. sound.soundTrackId = this.id;
  58503. };
  58504. SoundTrack.prototype.RemoveSound = function (sound) {
  58505. var index = this.soundCollection.indexOf(sound);
  58506. if (index !== -1) {
  58507. this.soundCollection.splice(index, 1);
  58508. }
  58509. };
  58510. SoundTrack.prototype.setVolume = function (newVolume) {
  58511. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58512. this._outputAudioNode.gain.value = newVolume;
  58513. }
  58514. };
  58515. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  58516. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58517. for (var i = 0; i < this.soundCollection.length; i++) {
  58518. this.soundCollection[i].switchPanningModelToHRTF();
  58519. }
  58520. }
  58521. };
  58522. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  58523. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58524. for (var i = 0; i < this.soundCollection.length; i++) {
  58525. this.soundCollection[i].switchPanningModelToEqualPower();
  58526. }
  58527. }
  58528. };
  58529. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  58530. if (this._connectedAnalyser) {
  58531. this._connectedAnalyser.stopDebugCanvas();
  58532. }
  58533. this._connectedAnalyser = analyser;
  58534. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58535. this._outputAudioNode.disconnect();
  58536. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  58537. }
  58538. };
  58539. return SoundTrack;
  58540. }());
  58541. BABYLON.SoundTrack = SoundTrack;
  58542. })(BABYLON || (BABYLON = {}));
  58543. //# sourceMappingURL=babylon.soundtrack.js.map
  58544. "use strict";
  58545. var BABYLON;
  58546. (function (BABYLON) {
  58547. var Analyser = /** @class */ (function () {
  58548. function Analyser(scene) {
  58549. this.SMOOTHING = 0.75;
  58550. this.FFT_SIZE = 512;
  58551. this.BARGRAPHAMPLITUDE = 256;
  58552. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  58553. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  58554. this._scene = scene;
  58555. this._audioEngine = BABYLON.Engine.audioEngine;
  58556. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  58557. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  58558. this._webAudioAnalyser.minDecibels = -140;
  58559. this._webAudioAnalyser.maxDecibels = 0;
  58560. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58561. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58562. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  58563. }
  58564. }
  58565. Analyser.prototype.getFrequencyBinCount = function () {
  58566. if (this._audioEngine.canUseWebAudio) {
  58567. return this._webAudioAnalyser.frequencyBinCount;
  58568. }
  58569. else {
  58570. return 0;
  58571. }
  58572. };
  58573. Analyser.prototype.getByteFrequencyData = function () {
  58574. if (this._audioEngine.canUseWebAudio) {
  58575. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58576. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58577. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  58578. }
  58579. return this._byteFreqs;
  58580. };
  58581. Analyser.prototype.getByteTimeDomainData = function () {
  58582. if (this._audioEngine.canUseWebAudio) {
  58583. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58584. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58585. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  58586. }
  58587. return this._byteTime;
  58588. };
  58589. Analyser.prototype.getFloatFrequencyData = function () {
  58590. if (this._audioEngine.canUseWebAudio) {
  58591. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58592. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58593. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  58594. }
  58595. return this._floatFreqs;
  58596. };
  58597. Analyser.prototype.drawDebugCanvas = function () {
  58598. var _this = this;
  58599. if (this._audioEngine.canUseWebAudio) {
  58600. if (!this._debugCanvas) {
  58601. this._debugCanvas = document.createElement("canvas");
  58602. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  58603. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  58604. this._debugCanvas.style.position = "absolute";
  58605. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  58606. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  58607. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  58608. document.body.appendChild(this._debugCanvas);
  58609. this._registerFunc = function () {
  58610. _this.drawDebugCanvas();
  58611. };
  58612. this._scene.registerBeforeRender(this._registerFunc);
  58613. }
  58614. if (this._registerFunc && this._debugCanvasContext) {
  58615. var workingArray = this.getByteFrequencyData();
  58616. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  58617. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  58618. // Draw the frequency domain chart.
  58619. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  58620. var value = workingArray[i];
  58621. var percent = value / this.BARGRAPHAMPLITUDE;
  58622. var height = this.DEBUGCANVASSIZE.height * percent;
  58623. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  58624. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  58625. var hue = i / this.getFrequencyBinCount() * 360;
  58626. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  58627. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  58628. }
  58629. }
  58630. }
  58631. };
  58632. Analyser.prototype.stopDebugCanvas = function () {
  58633. if (this._debugCanvas) {
  58634. if (this._registerFunc) {
  58635. this._scene.unregisterBeforeRender(this._registerFunc);
  58636. this._registerFunc = null;
  58637. }
  58638. document.body.removeChild(this._debugCanvas);
  58639. this._debugCanvas = null;
  58640. this._debugCanvasContext = null;
  58641. }
  58642. };
  58643. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  58644. if (this._audioEngine.canUseWebAudio) {
  58645. inputAudioNode.connect(this._webAudioAnalyser);
  58646. this._webAudioAnalyser.connect(outputAudioNode);
  58647. }
  58648. };
  58649. Analyser.prototype.dispose = function () {
  58650. if (this._audioEngine.canUseWebAudio) {
  58651. this._webAudioAnalyser.disconnect();
  58652. }
  58653. };
  58654. return Analyser;
  58655. }());
  58656. BABYLON.Analyser = Analyser;
  58657. })(BABYLON || (BABYLON = {}));
  58658. //# sourceMappingURL=babylon.analyser.js.map
  58659. "use strict";
  58660. var BABYLON;
  58661. (function (BABYLON) {
  58662. var CubeTexture = /** @class */ (function (_super) {
  58663. __extends(CubeTexture, _super);
  58664. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  58665. if (extensions === void 0) { extensions = null; }
  58666. if (noMipmap === void 0) { noMipmap = false; }
  58667. if (files === void 0) { files = null; }
  58668. if (onLoad === void 0) { onLoad = null; }
  58669. if (onError === void 0) { onError = null; }
  58670. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58671. if (prefiltered === void 0) { prefiltered = false; }
  58672. if (forcedExtension === void 0) { forcedExtension = null; }
  58673. var _this = _super.call(this, scene) || this;
  58674. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58675. /**
  58676. * Gets or sets the center of the bounding box associated with the cube texture
  58677. * It must define where the camera used to render the texture was set
  58678. */
  58679. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58680. _this.name = rootUrl;
  58681. _this.url = rootUrl;
  58682. _this._noMipmap = noMipmap;
  58683. _this.hasAlpha = false;
  58684. _this._format = format;
  58685. _this._prefiltered = prefiltered;
  58686. _this.isCube = true;
  58687. _this._textureMatrix = BABYLON.Matrix.Identity();
  58688. if (prefiltered) {
  58689. _this.gammaSpace = false;
  58690. }
  58691. if (!rootUrl && !files) {
  58692. return _this;
  58693. }
  58694. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  58695. var lastDot = rootUrl.lastIndexOf(".");
  58696. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  58697. var isDDS = (extension === ".dds");
  58698. if (!files) {
  58699. if (!isDDS && !extensions) {
  58700. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  58701. }
  58702. files = [];
  58703. if (extensions) {
  58704. for (var index = 0; index < extensions.length; index++) {
  58705. files.push(rootUrl + extensions[index]);
  58706. }
  58707. }
  58708. }
  58709. _this._files = files;
  58710. if (!_this._texture) {
  58711. if (!scene.useDelayedTextureLoading) {
  58712. if (prefiltered) {
  58713. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  58714. }
  58715. else {
  58716. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  58717. }
  58718. }
  58719. else {
  58720. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58721. }
  58722. }
  58723. else if (onLoad) {
  58724. if (_this._texture.isReady) {
  58725. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  58726. }
  58727. else {
  58728. _this._texture.onLoadedObservable.add(onLoad);
  58729. }
  58730. }
  58731. return _this;
  58732. }
  58733. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  58734. get: function () {
  58735. return this._boundingBoxSize;
  58736. },
  58737. /**
  58738. * Gets or sets the size of the bounding box associated with the cube texture
  58739. * When defined, the cubemap will switch to local mode
  58740. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58741. * @example https://www.babylonjs-playground.com/#RNASML
  58742. */
  58743. set: function (value) {
  58744. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58745. return;
  58746. }
  58747. this._boundingBoxSize = value;
  58748. var scene = this.getScene();
  58749. if (scene) {
  58750. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58751. }
  58752. },
  58753. enumerable: true,
  58754. configurable: true
  58755. });
  58756. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  58757. var rootUrlKey = "";
  58758. files.forEach(function (url) { return rootUrlKey += url; });
  58759. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  58760. };
  58761. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  58762. if (forcedExtension === void 0) { forcedExtension = null; }
  58763. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  58764. };
  58765. // Methods
  58766. CubeTexture.prototype.delayLoad = function () {
  58767. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58768. return;
  58769. }
  58770. var scene = this.getScene();
  58771. if (!scene) {
  58772. return;
  58773. }
  58774. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58775. this._texture = this._getFromCache(this.url, this._noMipmap);
  58776. if (!this._texture) {
  58777. if (this._prefiltered) {
  58778. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  58779. }
  58780. else {
  58781. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  58782. }
  58783. }
  58784. };
  58785. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  58786. return this._textureMatrix;
  58787. };
  58788. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58789. this._textureMatrix = value;
  58790. };
  58791. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58792. var texture = BABYLON.SerializationHelper.Parse(function () {
  58793. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  58794. }, parsedTexture, scene);
  58795. // Local Cubemaps
  58796. if (parsedTexture.boundingBoxPosition) {
  58797. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  58798. }
  58799. if (parsedTexture.boundingBoxSize) {
  58800. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  58801. }
  58802. // Animations
  58803. if (parsedTexture.animations) {
  58804. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  58805. var parsedAnimation = parsedTexture.animations[animationIndex];
  58806. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58807. }
  58808. }
  58809. return texture;
  58810. };
  58811. CubeTexture.prototype.clone = function () {
  58812. var _this = this;
  58813. return BABYLON.SerializationHelper.Clone(function () {
  58814. var scene = _this.getScene();
  58815. if (!scene) {
  58816. return _this;
  58817. }
  58818. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  58819. }, this);
  58820. };
  58821. return CubeTexture;
  58822. }(BABYLON.BaseTexture));
  58823. BABYLON.CubeTexture = CubeTexture;
  58824. })(BABYLON || (BABYLON = {}));
  58825. //# sourceMappingURL=babylon.cubeTexture.js.map
  58826. "use strict";
  58827. var BABYLON;
  58828. (function (BABYLON) {
  58829. var RenderTargetTexture = /** @class */ (function (_super) {
  58830. __extends(RenderTargetTexture, _super);
  58831. /**
  58832. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  58833. * or used a shadow, depth texture...
  58834. * @param name The friendly name of the texture
  58835. * @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)
  58836. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  58837. * @param generateMipMaps True if mip maps need to be generated after render.
  58838. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  58839. * @param type The type of the buffer in the RTT (int, half float, float...)
  58840. * @param isCube True if a cube texture needs to be created
  58841. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  58842. * @param generateDepthBuffer True to generate a depth buffer
  58843. * @param generateStencilBuffer True to generate a stencil buffer
  58844. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  58845. */
  58846. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  58847. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  58848. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58849. if (isCube === void 0) { isCube = false; }
  58850. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58851. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58852. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  58853. if (isMulti === void 0) { isMulti = false; }
  58854. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58855. _this.isCube = isCube;
  58856. /**
  58857. * Use this list to define the list of mesh you want to render.
  58858. */
  58859. _this.renderList = new Array();
  58860. _this.renderParticles = true;
  58861. _this.renderSprites = false;
  58862. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  58863. _this.ignoreCameraViewport = false;
  58864. // Events
  58865. /**
  58866. * An event triggered when the texture is unbind.
  58867. * @type {BABYLON.Observable}
  58868. */
  58869. _this.onBeforeBindObservable = new BABYLON.Observable();
  58870. /**
  58871. * An event triggered when the texture is unbind.
  58872. * @type {BABYLON.Observable}
  58873. */
  58874. _this.onAfterUnbindObservable = new BABYLON.Observable();
  58875. /**
  58876. * An event triggered before rendering the texture
  58877. * @type {BABYLON.Observable}
  58878. */
  58879. _this.onBeforeRenderObservable = new BABYLON.Observable();
  58880. /**
  58881. * An event triggered after rendering the texture
  58882. * @type {BABYLON.Observable}
  58883. */
  58884. _this.onAfterRenderObservable = new BABYLON.Observable();
  58885. /**
  58886. * An event triggered after the texture clear
  58887. * @type {BABYLON.Observable}
  58888. */
  58889. _this.onClearObservable = new BABYLON.Observable();
  58890. _this._currentRefreshId = -1;
  58891. _this._refreshRate = 1;
  58892. _this._samples = 1;
  58893. /**
  58894. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  58895. * It must define where the camera used to render the texture is set
  58896. */
  58897. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58898. scene = _this.getScene();
  58899. if (!scene) {
  58900. return _this;
  58901. }
  58902. _this._engine = scene.getEngine();
  58903. _this.name = name;
  58904. _this.isRenderTarget = true;
  58905. _this._initialSizeParameter = size;
  58906. _this._processSizeParameter(size);
  58907. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  58908. });
  58909. _this._generateMipMaps = generateMipMaps ? true : false;
  58910. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  58911. // Rendering groups
  58912. _this._renderingManager = new BABYLON.RenderingManager(scene);
  58913. if (isMulti) {
  58914. return _this;
  58915. }
  58916. _this._renderTargetOptions = {
  58917. generateMipMaps: generateMipMaps,
  58918. type: type,
  58919. samplingMode: samplingMode,
  58920. generateDepthBuffer: generateDepthBuffer,
  58921. generateStencilBuffer: generateStencilBuffer
  58922. };
  58923. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  58924. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58925. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58926. }
  58927. if (isCube) {
  58928. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  58929. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  58930. _this._textureMatrix = BABYLON.Matrix.Identity();
  58931. }
  58932. else {
  58933. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  58934. }
  58935. return _this;
  58936. }
  58937. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  58938. get: function () {
  58939. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  58940. },
  58941. enumerable: true,
  58942. configurable: true
  58943. });
  58944. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  58945. get: function () {
  58946. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  58947. },
  58948. enumerable: true,
  58949. configurable: true
  58950. });
  58951. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  58952. get: function () {
  58953. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  58954. },
  58955. enumerable: true,
  58956. configurable: true
  58957. });
  58958. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  58959. set: function (callback) {
  58960. if (this._onAfterUnbindObserver) {
  58961. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  58962. }
  58963. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  58964. },
  58965. enumerable: true,
  58966. configurable: true
  58967. });
  58968. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  58969. set: function (callback) {
  58970. if (this._onBeforeRenderObserver) {
  58971. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58972. }
  58973. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58974. },
  58975. enumerable: true,
  58976. configurable: true
  58977. });
  58978. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  58979. set: function (callback) {
  58980. if (this._onAfterRenderObserver) {
  58981. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58982. }
  58983. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58984. },
  58985. enumerable: true,
  58986. configurable: true
  58987. });
  58988. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  58989. set: function (callback) {
  58990. if (this._onClearObserver) {
  58991. this.onClearObservable.remove(this._onClearObserver);
  58992. }
  58993. this._onClearObserver = this.onClearObservable.add(callback);
  58994. },
  58995. enumerable: true,
  58996. configurable: true
  58997. });
  58998. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  58999. get: function () {
  59000. return this._renderTargetOptions;
  59001. },
  59002. enumerable: true,
  59003. configurable: true
  59004. });
  59005. RenderTargetTexture.prototype._onRatioRescale = function () {
  59006. if (this._sizeRatio) {
  59007. this.resize(this._initialSizeParameter);
  59008. }
  59009. };
  59010. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  59011. get: function () {
  59012. return this._boundingBoxSize;
  59013. },
  59014. /**
  59015. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  59016. * When defined, the cubemap will switch to local mode
  59017. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  59018. * @example https://www.babylonjs-playground.com/#RNASML
  59019. */
  59020. set: function (value) {
  59021. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  59022. return;
  59023. }
  59024. this._boundingBoxSize = value;
  59025. var scene = this.getScene();
  59026. if (scene) {
  59027. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  59028. }
  59029. },
  59030. enumerable: true,
  59031. configurable: true
  59032. });
  59033. /**
  59034. * Creates a depth stencil texture.
  59035. * This is only available in WebGL 2 or with the depth texture extension available.
  59036. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  59037. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  59038. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  59039. */
  59040. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  59041. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  59042. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  59043. if (generateStencil === void 0) { generateStencil = false; }
  59044. if (!this.getScene()) {
  59045. return;
  59046. }
  59047. var engine = this.getScene().getEngine();
  59048. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  59049. bilinearFiltering: bilinearFiltering,
  59050. comparisonFunction: comparisonFunction,
  59051. generateStencil: generateStencil,
  59052. isCube: this.isCube
  59053. });
  59054. engine.setFrameBufferDepthStencilTexture(this);
  59055. };
  59056. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  59057. if (size.ratio) {
  59058. this._sizeRatio = size.ratio;
  59059. this._size = {
  59060. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  59061. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  59062. };
  59063. }
  59064. else {
  59065. this._size = size;
  59066. }
  59067. };
  59068. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  59069. get: function () {
  59070. return this._samples;
  59071. },
  59072. set: function (value) {
  59073. if (this._samples === value) {
  59074. return;
  59075. }
  59076. var scene = this.getScene();
  59077. if (!scene) {
  59078. return;
  59079. }
  59080. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  59081. },
  59082. enumerable: true,
  59083. configurable: true
  59084. });
  59085. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  59086. this._currentRefreshId = -1;
  59087. };
  59088. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  59089. get: function () {
  59090. return this._refreshRate;
  59091. },
  59092. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  59093. set: function (value) {
  59094. this._refreshRate = value;
  59095. this.resetRefreshCounter();
  59096. },
  59097. enumerable: true,
  59098. configurable: true
  59099. });
  59100. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  59101. if (!this._postProcessManager) {
  59102. var scene = this.getScene();
  59103. if (!scene) {
  59104. return;
  59105. }
  59106. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  59107. this._postProcesses = new Array();
  59108. }
  59109. this._postProcesses.push(postProcess);
  59110. this._postProcesses[0].autoClear = false;
  59111. };
  59112. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  59113. if (!this._postProcesses) {
  59114. return;
  59115. }
  59116. if (dispose) {
  59117. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  59118. var postProcess = _a[_i];
  59119. postProcess.dispose();
  59120. }
  59121. }
  59122. this._postProcesses = [];
  59123. };
  59124. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  59125. if (!this._postProcesses) {
  59126. return;
  59127. }
  59128. var index = this._postProcesses.indexOf(postProcess);
  59129. if (index === -1) {
  59130. return;
  59131. }
  59132. this._postProcesses.splice(index, 1);
  59133. if (this._postProcesses.length > 0) {
  59134. this._postProcesses[0].autoClear = false;
  59135. }
  59136. };
  59137. RenderTargetTexture.prototype._shouldRender = function () {
  59138. if (this._currentRefreshId === -1) {
  59139. this._currentRefreshId = 1;
  59140. return true;
  59141. }
  59142. if (this.refreshRate === this._currentRefreshId) {
  59143. this._currentRefreshId = 1;
  59144. return true;
  59145. }
  59146. this._currentRefreshId++;
  59147. return false;
  59148. };
  59149. RenderTargetTexture.prototype.getRenderSize = function () {
  59150. if (this._size.width) {
  59151. return this._size.width;
  59152. }
  59153. return this._size;
  59154. };
  59155. RenderTargetTexture.prototype.getRenderWidth = function () {
  59156. if (this._size.width) {
  59157. return this._size.width;
  59158. }
  59159. return this._size;
  59160. };
  59161. RenderTargetTexture.prototype.getRenderHeight = function () {
  59162. if (this._size.width) {
  59163. return this._size.height;
  59164. }
  59165. return this._size;
  59166. };
  59167. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  59168. get: function () {
  59169. return true;
  59170. },
  59171. enumerable: true,
  59172. configurable: true
  59173. });
  59174. RenderTargetTexture.prototype.scale = function (ratio) {
  59175. var newSize = this.getRenderSize() * ratio;
  59176. this.resize(newSize);
  59177. };
  59178. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  59179. if (this.isCube) {
  59180. return this._textureMatrix;
  59181. }
  59182. return _super.prototype.getReflectionTextureMatrix.call(this);
  59183. };
  59184. RenderTargetTexture.prototype.resize = function (size) {
  59185. this.releaseInternalTexture();
  59186. var scene = this.getScene();
  59187. if (!scene) {
  59188. return;
  59189. }
  59190. this._processSizeParameter(size);
  59191. if (this.isCube) {
  59192. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  59193. }
  59194. else {
  59195. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  59196. }
  59197. };
  59198. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  59199. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  59200. if (dumpForDebug === void 0) { dumpForDebug = false; }
  59201. var scene = this.getScene();
  59202. if (!scene) {
  59203. return;
  59204. }
  59205. var engine = scene.getEngine();
  59206. if (this.useCameraPostProcesses !== undefined) {
  59207. useCameraPostProcess = this.useCameraPostProcesses;
  59208. }
  59209. if (this._waitingRenderList) {
  59210. this.renderList = [];
  59211. for (var index = 0; index < this._waitingRenderList.length; index++) {
  59212. var id = this._waitingRenderList[index];
  59213. var mesh_1 = scene.getMeshByID(id);
  59214. if (mesh_1) {
  59215. this.renderList.push(mesh_1);
  59216. }
  59217. }
  59218. delete this._waitingRenderList;
  59219. }
  59220. // Is predicate defined?
  59221. if (this.renderListPredicate) {
  59222. if (this.renderList) {
  59223. this.renderList.splice(0); // Clear previous renderList
  59224. }
  59225. else {
  59226. this.renderList = [];
  59227. }
  59228. var scene = this.getScene();
  59229. if (!scene) {
  59230. return;
  59231. }
  59232. var sceneMeshes = scene.meshes;
  59233. for (var index = 0; index < sceneMeshes.length; index++) {
  59234. var mesh = sceneMeshes[index];
  59235. if (this.renderListPredicate(mesh)) {
  59236. this.renderList.push(mesh);
  59237. }
  59238. }
  59239. }
  59240. this.onBeforeBindObservable.notifyObservers(this);
  59241. // Set custom projection.
  59242. // Needs to be before binding to prevent changing the aspect ratio.
  59243. var camera;
  59244. if (this.activeCamera) {
  59245. camera = this.activeCamera;
  59246. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59247. if (this.activeCamera !== scene.activeCamera) {
  59248. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  59249. }
  59250. }
  59251. else {
  59252. camera = scene.activeCamera;
  59253. if (camera) {
  59254. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59255. }
  59256. }
  59257. // Prepare renderingManager
  59258. this._renderingManager.reset();
  59259. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  59260. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  59261. var sceneRenderId = scene.getRenderId();
  59262. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  59263. var mesh = currentRenderList[meshIndex];
  59264. if (mesh) {
  59265. if (!mesh.isReady(this.refreshRate === 0)) {
  59266. this.resetRefreshCounter();
  59267. continue;
  59268. }
  59269. mesh._preActivateForIntermediateRendering(sceneRenderId);
  59270. var isMasked = void 0;
  59271. if (!this.renderList && camera) {
  59272. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  59273. }
  59274. else {
  59275. isMasked = false;
  59276. }
  59277. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  59278. mesh._activate(sceneRenderId);
  59279. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  59280. var subMesh = mesh.subMeshes[subIndex];
  59281. scene._activeIndices.addCount(subMesh.indexCount, false);
  59282. this._renderingManager.dispatch(subMesh, mesh);
  59283. }
  59284. }
  59285. }
  59286. }
  59287. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  59288. var particleSystem = scene.particleSystems[particleIndex];
  59289. var emitter = particleSystem.emitter;
  59290. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  59291. continue;
  59292. }
  59293. if (currentRenderList.indexOf(emitter) >= 0) {
  59294. this._renderingManager.dispatchParticles(particleSystem);
  59295. }
  59296. }
  59297. if (this.isCube) {
  59298. for (var face = 0; face < 6; face++) {
  59299. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59300. scene.incrementRenderId();
  59301. scene.resetCachedMaterial();
  59302. }
  59303. }
  59304. else {
  59305. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59306. }
  59307. this.onAfterUnbindObservable.notifyObservers(this);
  59308. if (scene.activeCamera) {
  59309. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  59310. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  59311. }
  59312. engine.setViewport(scene.activeCamera.viewport);
  59313. }
  59314. scene.resetCachedMaterial();
  59315. };
  59316. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  59317. var minimum = 128;
  59318. var x = renderDimension * scale;
  59319. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  59320. // Ensure we don't exceed the render dimension (while staying POT)
  59321. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  59322. };
  59323. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59324. var _this = this;
  59325. if (!this._texture) {
  59326. return;
  59327. }
  59328. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  59329. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59330. });
  59331. };
  59332. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  59333. var scene = this.getScene();
  59334. if (!scene) {
  59335. return;
  59336. }
  59337. var engine = scene.getEngine();
  59338. if (!this._texture) {
  59339. return;
  59340. }
  59341. // Bind
  59342. if (this._postProcessManager) {
  59343. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  59344. }
  59345. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  59346. if (this._texture) {
  59347. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  59348. }
  59349. }
  59350. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  59351. // Clear
  59352. if (this.onClearObservable.hasObservers()) {
  59353. this.onClearObservable.notifyObservers(engine);
  59354. }
  59355. else {
  59356. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  59357. }
  59358. if (!this._doNotChangeAspectRatio) {
  59359. scene.updateTransformMatrix(true);
  59360. }
  59361. // Render
  59362. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  59363. if (this._postProcessManager) {
  59364. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  59365. }
  59366. else if (useCameraPostProcess) {
  59367. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  59368. }
  59369. if (!this._doNotChangeAspectRatio) {
  59370. scene.updateTransformMatrix(true);
  59371. }
  59372. // Dump ?
  59373. if (dumpForDebug) {
  59374. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  59375. }
  59376. // Unbind
  59377. if (!this.isCube || faceIndex === 5) {
  59378. if (this.isCube) {
  59379. if (faceIndex === 5) {
  59380. engine.generateMipMapsForCubemap(this._texture);
  59381. }
  59382. }
  59383. this.unbindFrameBuffer(engine, faceIndex);
  59384. }
  59385. else {
  59386. this.onAfterRenderObservable.notifyObservers(faceIndex);
  59387. }
  59388. };
  59389. /**
  59390. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  59391. * This allowed control for front to back rendering or reversly depending of the special needs.
  59392. *
  59393. * @param renderingGroupId The rendering group id corresponding to its index
  59394. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  59395. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  59396. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  59397. */
  59398. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  59399. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  59400. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  59401. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  59402. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  59403. };
  59404. /**
  59405. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  59406. *
  59407. * @param renderingGroupId The rendering group id corresponding to its index
  59408. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  59409. */
  59410. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  59411. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  59412. };
  59413. RenderTargetTexture.prototype.clone = function () {
  59414. var textureSize = this.getSize();
  59415. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  59416. // Base texture
  59417. newTexture.hasAlpha = this.hasAlpha;
  59418. newTexture.level = this.level;
  59419. // RenderTarget Texture
  59420. newTexture.coordinatesMode = this.coordinatesMode;
  59421. if (this.renderList) {
  59422. newTexture.renderList = this.renderList.slice(0);
  59423. }
  59424. return newTexture;
  59425. };
  59426. RenderTargetTexture.prototype.serialize = function () {
  59427. if (!this.name) {
  59428. return null;
  59429. }
  59430. var serializationObject = _super.prototype.serialize.call(this);
  59431. serializationObject.renderTargetSize = this.getRenderSize();
  59432. serializationObject.renderList = [];
  59433. if (this.renderList) {
  59434. for (var index = 0; index < this.renderList.length; index++) {
  59435. serializationObject.renderList.push(this.renderList[index].id);
  59436. }
  59437. }
  59438. return serializationObject;
  59439. };
  59440. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  59441. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  59442. var objBuffer = this.getInternalTexture();
  59443. var scene = this.getScene();
  59444. if (objBuffer && scene) {
  59445. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  59446. }
  59447. };
  59448. RenderTargetTexture.prototype.dispose = function () {
  59449. if (this._postProcessManager) {
  59450. this._postProcessManager.dispose();
  59451. this._postProcessManager = null;
  59452. }
  59453. this.clearPostProcesses(true);
  59454. if (this._resizeObserver) {
  59455. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  59456. this._resizeObserver = null;
  59457. }
  59458. this.renderList = null;
  59459. // Remove from custom render targets
  59460. var scene = this.getScene();
  59461. if (!scene) {
  59462. return;
  59463. }
  59464. var index = scene.customRenderTargets.indexOf(this);
  59465. if (index >= 0) {
  59466. scene.customRenderTargets.splice(index, 1);
  59467. }
  59468. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  59469. var camera = _a[_i];
  59470. index = camera.customRenderTargets.indexOf(this);
  59471. if (index >= 0) {
  59472. camera.customRenderTargets.splice(index, 1);
  59473. }
  59474. }
  59475. _super.prototype.dispose.call(this);
  59476. };
  59477. RenderTargetTexture.prototype._rebuild = function () {
  59478. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  59479. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  59480. }
  59481. if (this._postProcessManager) {
  59482. this._postProcessManager._rebuild();
  59483. }
  59484. };
  59485. /**
  59486. * Clear the info related to rendering groups preventing retention point in material dispose.
  59487. */
  59488. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  59489. if (this._renderingManager) {
  59490. this._renderingManager.freeRenderingGroups();
  59491. }
  59492. };
  59493. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  59494. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  59495. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  59496. return RenderTargetTexture;
  59497. }(BABYLON.Texture));
  59498. BABYLON.RenderTargetTexture = RenderTargetTexture;
  59499. })(BABYLON || (BABYLON = {}));
  59500. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  59501. "use strict";
  59502. var BABYLON;
  59503. (function (BABYLON) {
  59504. ;
  59505. var MultiRenderTarget = /** @class */ (function (_super) {
  59506. __extends(MultiRenderTarget, _super);
  59507. function MultiRenderTarget(name, size, count, scene, options) {
  59508. var _this = this;
  59509. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  59510. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  59511. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  59512. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  59513. _this._engine = scene.getEngine();
  59514. if (!_this.isSupported) {
  59515. _this.dispose();
  59516. return;
  59517. }
  59518. var types = [];
  59519. var samplingModes = [];
  59520. for (var i = 0; i < count; i++) {
  59521. if (options && options.types && options.types[i] !== undefined) {
  59522. types.push(options.types[i]);
  59523. }
  59524. else {
  59525. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59526. }
  59527. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  59528. samplingModes.push(options.samplingModes[i]);
  59529. }
  59530. else {
  59531. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59532. }
  59533. }
  59534. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  59535. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  59536. _this._size = size;
  59537. _this._multiRenderTargetOptions = {
  59538. samplingModes: samplingModes,
  59539. generateMipMaps: generateMipMaps,
  59540. generateDepthBuffer: generateDepthBuffer,
  59541. generateStencilBuffer: generateStencilBuffer,
  59542. generateDepthTexture: generateDepthTexture,
  59543. types: types,
  59544. textureCount: count
  59545. };
  59546. _this._createInternalTextures();
  59547. _this._createTextures();
  59548. return _this;
  59549. }
  59550. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  59551. get: function () {
  59552. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  59553. },
  59554. enumerable: true,
  59555. configurable: true
  59556. });
  59557. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  59558. get: function () {
  59559. return this._textures;
  59560. },
  59561. enumerable: true,
  59562. configurable: true
  59563. });
  59564. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  59565. get: function () {
  59566. return this._textures[this._textures.length - 1];
  59567. },
  59568. enumerable: true,
  59569. configurable: true
  59570. });
  59571. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  59572. set: function (wrap) {
  59573. if (this._textures) {
  59574. for (var i = 0; i < this._textures.length; i++) {
  59575. this._textures[i].wrapU = wrap;
  59576. }
  59577. }
  59578. },
  59579. enumerable: true,
  59580. configurable: true
  59581. });
  59582. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  59583. set: function (wrap) {
  59584. if (this._textures) {
  59585. for (var i = 0; i < this._textures.length; i++) {
  59586. this._textures[i].wrapV = wrap;
  59587. }
  59588. }
  59589. },
  59590. enumerable: true,
  59591. configurable: true
  59592. });
  59593. MultiRenderTarget.prototype._rebuild = function () {
  59594. this.releaseInternalTextures();
  59595. this._createInternalTextures();
  59596. for (var i = 0; i < this._internalTextures.length; i++) {
  59597. var texture = this._textures[i];
  59598. texture._texture = this._internalTextures[i];
  59599. }
  59600. // Keeps references to frame buffer and stencil/depth buffer
  59601. this._texture = this._internalTextures[0];
  59602. };
  59603. MultiRenderTarget.prototype._createInternalTextures = function () {
  59604. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  59605. };
  59606. MultiRenderTarget.prototype._createTextures = function () {
  59607. this._textures = [];
  59608. for (var i = 0; i < this._internalTextures.length; i++) {
  59609. var texture = new BABYLON.Texture(null, this.getScene());
  59610. texture._texture = this._internalTextures[i];
  59611. this._textures.push(texture);
  59612. }
  59613. // Keeps references to frame buffer and stencil/depth buffer
  59614. this._texture = this._internalTextures[0];
  59615. };
  59616. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  59617. get: function () {
  59618. return this._samples;
  59619. },
  59620. set: function (value) {
  59621. if (this._samples === value) {
  59622. return;
  59623. }
  59624. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  59625. },
  59626. enumerable: true,
  59627. configurable: true
  59628. });
  59629. MultiRenderTarget.prototype.resize = function (size) {
  59630. this.releaseInternalTextures();
  59631. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  59632. this._createInternalTextures();
  59633. };
  59634. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59635. var _this = this;
  59636. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  59637. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59638. });
  59639. };
  59640. MultiRenderTarget.prototype.dispose = function () {
  59641. this.releaseInternalTextures();
  59642. _super.prototype.dispose.call(this);
  59643. };
  59644. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  59645. if (!this._internalTextures) {
  59646. return;
  59647. }
  59648. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  59649. if (this._internalTextures[i] !== undefined) {
  59650. this._internalTextures[i].dispose();
  59651. this._internalTextures.splice(i, 1);
  59652. }
  59653. }
  59654. };
  59655. return MultiRenderTarget;
  59656. }(BABYLON.RenderTargetTexture));
  59657. BABYLON.MultiRenderTarget = MultiRenderTarget;
  59658. })(BABYLON || (BABYLON = {}));
  59659. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  59660. "use strict";
  59661. var BABYLON;
  59662. (function (BABYLON) {
  59663. var MirrorTexture = /** @class */ (function (_super) {
  59664. __extends(MirrorTexture, _super);
  59665. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  59666. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59667. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59668. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59669. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  59670. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  59671. _this._transformMatrix = BABYLON.Matrix.Zero();
  59672. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  59673. _this._adaptiveBlurKernel = 0;
  59674. _this._blurKernelX = 0;
  59675. _this._blurKernelY = 0;
  59676. _this._blurRatio = 1.0;
  59677. _this.ignoreCameraViewport = true;
  59678. _this.onBeforeRenderObservable.add(function () {
  59679. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  59680. _this._savedViewMatrix = scene.getViewMatrix();
  59681. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  59682. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  59683. scene.clipPlane = _this.mirrorPlane;
  59684. scene.getEngine().cullBackFaces = false;
  59685. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  59686. });
  59687. _this.onAfterRenderObservable.add(function () {
  59688. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  59689. scene.getEngine().cullBackFaces = true;
  59690. scene._mirroredCameraPosition = null;
  59691. delete scene.clipPlane;
  59692. });
  59693. return _this;
  59694. }
  59695. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  59696. get: function () {
  59697. return this._blurRatio;
  59698. },
  59699. set: function (value) {
  59700. if (this._blurRatio === value) {
  59701. return;
  59702. }
  59703. this._blurRatio = value;
  59704. this._preparePostProcesses();
  59705. },
  59706. enumerable: true,
  59707. configurable: true
  59708. });
  59709. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  59710. set: function (value) {
  59711. this._adaptiveBlurKernel = value;
  59712. this._autoComputeBlurKernel();
  59713. },
  59714. enumerable: true,
  59715. configurable: true
  59716. });
  59717. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  59718. set: function (value) {
  59719. this.blurKernelX = value;
  59720. this.blurKernelY = value;
  59721. },
  59722. enumerable: true,
  59723. configurable: true
  59724. });
  59725. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  59726. get: function () {
  59727. return this._blurKernelX;
  59728. },
  59729. set: function (value) {
  59730. if (this._blurKernelX === value) {
  59731. return;
  59732. }
  59733. this._blurKernelX = value;
  59734. this._preparePostProcesses();
  59735. },
  59736. enumerable: true,
  59737. configurable: true
  59738. });
  59739. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  59740. get: function () {
  59741. return this._blurKernelY;
  59742. },
  59743. set: function (value) {
  59744. if (this._blurKernelY === value) {
  59745. return;
  59746. }
  59747. this._blurKernelY = value;
  59748. this._preparePostProcesses();
  59749. },
  59750. enumerable: true,
  59751. configurable: true
  59752. });
  59753. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  59754. var engine = this.getScene().getEngine();
  59755. var dw = this.getRenderWidth() / engine.getRenderWidth();
  59756. var dh = this.getRenderHeight() / engine.getRenderHeight();
  59757. this.blurKernelX = this._adaptiveBlurKernel * dw;
  59758. this.blurKernelY = this._adaptiveBlurKernel * dh;
  59759. };
  59760. MirrorTexture.prototype._onRatioRescale = function () {
  59761. if (this._sizeRatio) {
  59762. this.resize(this._initialSizeParameter);
  59763. if (!this._adaptiveBlurKernel) {
  59764. this._preparePostProcesses();
  59765. }
  59766. }
  59767. if (this._adaptiveBlurKernel) {
  59768. this._autoComputeBlurKernel();
  59769. }
  59770. };
  59771. MirrorTexture.prototype._preparePostProcesses = function () {
  59772. this.clearPostProcesses(true);
  59773. if (this._blurKernelX && this._blurKernelY) {
  59774. var engine = this.getScene().getEngine();
  59775. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59776. 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);
  59777. this._blurX.autoClear = false;
  59778. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  59779. this._blurX.inputTexture = this._texture;
  59780. }
  59781. else {
  59782. this._blurX.alwaysForcePOT = true;
  59783. }
  59784. 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);
  59785. this._blurY.autoClear = false;
  59786. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  59787. this.addPostProcess(this._blurX);
  59788. this.addPostProcess(this._blurY);
  59789. }
  59790. else {
  59791. if (this._blurY) {
  59792. this.removePostProcess(this._blurY);
  59793. this._blurY.dispose();
  59794. this._blurY = null;
  59795. }
  59796. if (this._blurX) {
  59797. this.removePostProcess(this._blurX);
  59798. this._blurX.dispose();
  59799. this._blurX = null;
  59800. }
  59801. }
  59802. };
  59803. MirrorTexture.prototype.clone = function () {
  59804. var scene = this.getScene();
  59805. if (!scene) {
  59806. return this;
  59807. }
  59808. var textureSize = this.getSize();
  59809. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  59810. // Base texture
  59811. newTexture.hasAlpha = this.hasAlpha;
  59812. newTexture.level = this.level;
  59813. // Mirror Texture
  59814. newTexture.mirrorPlane = this.mirrorPlane.clone();
  59815. if (this.renderList) {
  59816. newTexture.renderList = this.renderList.slice(0);
  59817. }
  59818. return newTexture;
  59819. };
  59820. MirrorTexture.prototype.serialize = function () {
  59821. if (!this.name) {
  59822. return null;
  59823. }
  59824. var serializationObject = _super.prototype.serialize.call(this);
  59825. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  59826. return serializationObject;
  59827. };
  59828. return MirrorTexture;
  59829. }(BABYLON.RenderTargetTexture));
  59830. BABYLON.MirrorTexture = MirrorTexture;
  59831. })(BABYLON || (BABYLON = {}));
  59832. //# sourceMappingURL=babylon.mirrorTexture.js.map
  59833. "use strict";
  59834. var BABYLON;
  59835. (function (BABYLON) {
  59836. /**
  59837. * Creates a refraction texture used by refraction channel of the standard material.
  59838. * @param name the texture name
  59839. * @param size size of the underlying texture
  59840. * @param scene root scene
  59841. */
  59842. var RefractionTexture = /** @class */ (function (_super) {
  59843. __extends(RefractionTexture, _super);
  59844. function RefractionTexture(name, size, scene, generateMipMaps) {
  59845. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  59846. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  59847. _this.depth = 2.0;
  59848. _this.onBeforeRenderObservable.add(function () {
  59849. scene.clipPlane = _this.refractionPlane;
  59850. });
  59851. _this.onAfterRenderObservable.add(function () {
  59852. delete scene.clipPlane;
  59853. });
  59854. return _this;
  59855. }
  59856. RefractionTexture.prototype.clone = function () {
  59857. var scene = this.getScene();
  59858. if (!scene) {
  59859. return this;
  59860. }
  59861. var textureSize = this.getSize();
  59862. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  59863. // Base texture
  59864. newTexture.hasAlpha = this.hasAlpha;
  59865. newTexture.level = this.level;
  59866. // Refraction Texture
  59867. newTexture.refractionPlane = this.refractionPlane.clone();
  59868. if (this.renderList) {
  59869. newTexture.renderList = this.renderList.slice(0);
  59870. }
  59871. newTexture.depth = this.depth;
  59872. return newTexture;
  59873. };
  59874. RefractionTexture.prototype.serialize = function () {
  59875. if (!this.name) {
  59876. return null;
  59877. }
  59878. var serializationObject = _super.prototype.serialize.call(this);
  59879. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  59880. serializationObject.depth = this.depth;
  59881. return serializationObject;
  59882. };
  59883. return RefractionTexture;
  59884. }(BABYLON.RenderTargetTexture));
  59885. BABYLON.RefractionTexture = RefractionTexture;
  59886. })(BABYLON || (BABYLON = {}));
  59887. //# sourceMappingURL=babylon.refractionTexture.js.map
  59888. "use strict";
  59889. var BABYLON;
  59890. (function (BABYLON) {
  59891. var DynamicTexture = /** @class */ (function (_super) {
  59892. __extends(DynamicTexture, _super);
  59893. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  59894. if (scene === void 0) { scene = null; }
  59895. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59896. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  59897. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  59898. _this.name = name;
  59899. _this._engine = _this.getScene().getEngine();
  59900. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59901. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59902. _this._generateMipMaps = generateMipMaps;
  59903. if (options.getContext) {
  59904. _this._canvas = options;
  59905. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59906. }
  59907. else {
  59908. _this._canvas = document.createElement("canvas");
  59909. if (options.width) {
  59910. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59911. }
  59912. else {
  59913. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  59914. }
  59915. }
  59916. var textureSize = _this.getSize();
  59917. _this._canvas.width = textureSize.width;
  59918. _this._canvas.height = textureSize.height;
  59919. _this._context = _this._canvas.getContext("2d");
  59920. return _this;
  59921. }
  59922. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  59923. get: function () {
  59924. return true;
  59925. },
  59926. enumerable: true,
  59927. configurable: true
  59928. });
  59929. DynamicTexture.prototype._recreate = function (textureSize) {
  59930. this._canvas.width = textureSize.width;
  59931. this._canvas.height = textureSize.height;
  59932. this.releaseInternalTexture();
  59933. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  59934. };
  59935. DynamicTexture.prototype.scale = function (ratio) {
  59936. var textureSize = this.getSize();
  59937. textureSize.width *= ratio;
  59938. textureSize.height *= ratio;
  59939. this._recreate(textureSize);
  59940. };
  59941. DynamicTexture.prototype.scaleTo = function (width, height) {
  59942. var textureSize = this.getSize();
  59943. textureSize.width = width;
  59944. textureSize.height = height;
  59945. this._recreate(textureSize);
  59946. };
  59947. DynamicTexture.prototype.getContext = function () {
  59948. return this._context;
  59949. };
  59950. DynamicTexture.prototype.clear = function () {
  59951. var size = this.getSize();
  59952. this._context.fillRect(0, 0, size.width, size.height);
  59953. };
  59954. DynamicTexture.prototype.update = function (invertY) {
  59955. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  59956. };
  59957. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  59958. if (update === void 0) { update = true; }
  59959. var size = this.getSize();
  59960. if (clearColor) {
  59961. this._context.fillStyle = clearColor;
  59962. this._context.fillRect(0, 0, size.width, size.height);
  59963. }
  59964. this._context.font = font;
  59965. if (x === null || x === undefined) {
  59966. var textSize = this._context.measureText(text);
  59967. x = (size.width - textSize.width) / 2;
  59968. }
  59969. if (y === null || y === undefined) {
  59970. var fontSize = parseInt((font.replace(/\D/g, '')));
  59971. ;
  59972. y = (size.height / 2) + (fontSize / 3.65);
  59973. }
  59974. this._context.fillStyle = color;
  59975. this._context.fillText(text, x, y);
  59976. if (update) {
  59977. this.update(invertY);
  59978. }
  59979. };
  59980. DynamicTexture.prototype.clone = function () {
  59981. var scene = this.getScene();
  59982. if (!scene) {
  59983. return this;
  59984. }
  59985. var textureSize = this.getSize();
  59986. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  59987. // Base texture
  59988. newTexture.hasAlpha = this.hasAlpha;
  59989. newTexture.level = this.level;
  59990. // Dynamic Texture
  59991. newTexture.wrapU = this.wrapU;
  59992. newTexture.wrapV = this.wrapV;
  59993. return newTexture;
  59994. };
  59995. DynamicTexture.prototype._rebuild = function () {
  59996. this.update();
  59997. };
  59998. return DynamicTexture;
  59999. }(BABYLON.Texture));
  60000. BABYLON.DynamicTexture = DynamicTexture;
  60001. })(BABYLON || (BABYLON = {}));
  60002. //# sourceMappingURL=babylon.dynamicTexture.js.map
  60003. "use strict";
  60004. var BABYLON;
  60005. (function (BABYLON) {
  60006. var VideoTexture = /** @class */ (function (_super) {
  60007. __extends(VideoTexture, _super);
  60008. /**
  60009. * Creates a video texture.
  60010. * Sample : https://doc.babylonjs.com/how_to/video_texture
  60011. * @param {string | null} name optional name, will detect from video source, if not defined
  60012. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  60013. * @param {BABYLON.Scene} scene is obviously the current scene.
  60014. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  60015. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  60016. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  60017. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  60018. */
  60019. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  60020. if (generateMipMaps === void 0) { generateMipMaps = false; }
  60021. if (invertY === void 0) { invertY = false; }
  60022. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60023. if (settings === void 0) { settings = {
  60024. autoPlay: true,
  60025. loop: true,
  60026. autoUpdateTexture: true,
  60027. }; }
  60028. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60029. _this._createInternalTexture = function () {
  60030. if (_this._texture != null) {
  60031. return;
  60032. }
  60033. if (!_this._engine.needPOTTextures ||
  60034. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  60035. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60036. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60037. }
  60038. else {
  60039. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60040. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60041. _this._generateMipMaps = false;
  60042. }
  60043. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  60044. _this._texture.isReady = true;
  60045. _this._updateInternalTexture();
  60046. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  60047. _this.onLoadObservable.notifyObservers(_this);
  60048. }
  60049. };
  60050. _this.reset = function () {
  60051. if (_this._texture == null) {
  60052. return;
  60053. }
  60054. _this._texture.dispose();
  60055. _this._texture = null;
  60056. };
  60057. _this._updateInternalTexture = function (e) {
  60058. if (_this._texture == null || !_this._texture.isReady) {
  60059. return;
  60060. }
  60061. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  60062. return;
  60063. }
  60064. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  60065. };
  60066. _this._engine = _this.getScene().getEngine();
  60067. _this._generateMipMaps = generateMipMaps;
  60068. _this._samplingMode = samplingMode;
  60069. _this.autoUpdateTexture = settings.autoUpdateTexture;
  60070. _this.name = name || _this._getName(src);
  60071. _this.video = _this._getVideo(src);
  60072. if (settings.autoPlay !== undefined) {
  60073. _this.video.autoplay = settings.autoPlay;
  60074. }
  60075. if (settings.loop !== undefined) {
  60076. _this.video.loop = settings.loop;
  60077. }
  60078. _this.video.addEventListener("canplay", _this._createInternalTexture);
  60079. _this.video.addEventListener("paused", _this._updateInternalTexture);
  60080. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  60081. _this.video.addEventListener("emptied", _this.reset);
  60082. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  60083. _this._createInternalTexture();
  60084. }
  60085. return _this;
  60086. }
  60087. VideoTexture.prototype._getName = function (src) {
  60088. if (src instanceof HTMLVideoElement) {
  60089. return src.currentSrc;
  60090. }
  60091. if (typeof src === "object") {
  60092. return src.toString();
  60093. }
  60094. return src;
  60095. };
  60096. ;
  60097. VideoTexture.prototype._getVideo = function (src) {
  60098. if (src instanceof HTMLVideoElement) {
  60099. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  60100. return src;
  60101. }
  60102. var video = document.createElement("video");
  60103. if (typeof src === "string") {
  60104. BABYLON.Tools.SetCorsBehavior(src, video);
  60105. video.src = src;
  60106. }
  60107. else {
  60108. BABYLON.Tools.SetCorsBehavior(src[0], video);
  60109. src.forEach(function (url) {
  60110. var source = document.createElement("source");
  60111. source.src = url;
  60112. video.appendChild(source);
  60113. });
  60114. }
  60115. return video;
  60116. };
  60117. ;
  60118. /**
  60119. * Internal method to initiate `update`.
  60120. */
  60121. VideoTexture.prototype._rebuild = function () {
  60122. this.update();
  60123. };
  60124. /**
  60125. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  60126. */
  60127. VideoTexture.prototype.update = function () {
  60128. if (!this.autoUpdateTexture) {
  60129. // Expecting user to call `updateTexture` manually
  60130. return;
  60131. }
  60132. this.updateTexture(true);
  60133. };
  60134. /**
  60135. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  60136. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  60137. */
  60138. VideoTexture.prototype.updateTexture = function (isVisible) {
  60139. if (!isVisible) {
  60140. return;
  60141. }
  60142. if (this.video.paused) {
  60143. return;
  60144. }
  60145. this._updateInternalTexture();
  60146. };
  60147. /**
  60148. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  60149. * @param url New url.
  60150. */
  60151. VideoTexture.prototype.updateURL = function (url) {
  60152. this.video.src = url;
  60153. };
  60154. VideoTexture.prototype.dispose = function () {
  60155. _super.prototype.dispose.call(this);
  60156. this.video.removeEventListener("canplay", this._createInternalTexture);
  60157. this.video.removeEventListener("paused", this._updateInternalTexture);
  60158. this.video.removeEventListener("seeked", this._updateInternalTexture);
  60159. this.video.removeEventListener("emptied", this.reset);
  60160. this.video.pause();
  60161. };
  60162. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  60163. var video = document.createElement("video");
  60164. var constraintsDeviceId;
  60165. if (constraints && constraints.deviceId) {
  60166. constraintsDeviceId = {
  60167. exact: constraints.deviceId,
  60168. };
  60169. }
  60170. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  60171. if (navigator.mediaDevices) {
  60172. navigator.mediaDevices.getUserMedia({ video: constraints })
  60173. .then(function (stream) {
  60174. if (video.mozSrcObject !== undefined) {
  60175. // hack for Firefox < 19
  60176. video.mozSrcObject = stream;
  60177. }
  60178. else {
  60179. video.srcObject = stream;
  60180. }
  60181. var onPlaying = function () {
  60182. if (onReady) {
  60183. onReady(new VideoTexture("video", video, scene, true, true));
  60184. }
  60185. video.removeEventListener("playing", onPlaying);
  60186. };
  60187. video.addEventListener("playing", onPlaying);
  60188. video.play();
  60189. })
  60190. .catch(function (err) {
  60191. BABYLON.Tools.Error(err.name);
  60192. });
  60193. }
  60194. else {
  60195. navigator.getUserMedia =
  60196. navigator.getUserMedia ||
  60197. navigator.webkitGetUserMedia ||
  60198. navigator.mozGetUserMedia ||
  60199. navigator.msGetUserMedia;
  60200. if (navigator.getUserMedia) {
  60201. navigator.getUserMedia({
  60202. video: {
  60203. deviceId: constraintsDeviceId,
  60204. width: {
  60205. min: (constraints && constraints.minWidth) || 256,
  60206. max: (constraints && constraints.maxWidth) || 640,
  60207. },
  60208. height: {
  60209. min: (constraints && constraints.minHeight) || 256,
  60210. max: (constraints && constraints.maxHeight) || 480,
  60211. },
  60212. },
  60213. }, function (stream) {
  60214. if (video.mozSrcObject !== undefined) {
  60215. // hack for Firefox < 19
  60216. video.mozSrcObject = stream;
  60217. }
  60218. else {
  60219. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  60220. }
  60221. video.play();
  60222. if (onReady) {
  60223. onReady(new VideoTexture("video", video, scene, true, true));
  60224. }
  60225. }, function (e) {
  60226. BABYLON.Tools.Error(e.name);
  60227. });
  60228. }
  60229. }
  60230. };
  60231. return VideoTexture;
  60232. }(BABYLON.Texture));
  60233. BABYLON.VideoTexture = VideoTexture;
  60234. })(BABYLON || (BABYLON = {}));
  60235. //# sourceMappingURL=babylon.videoTexture.js.map
  60236. "use strict";
  60237. var BABYLON;
  60238. (function (BABYLON) {
  60239. var RawTexture = /** @class */ (function (_super) {
  60240. __extends(RawTexture, _super);
  60241. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  60242. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60243. if (invertY === void 0) { invertY = false; }
  60244. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60245. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60246. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60247. _this.format = format;
  60248. _this._engine = scene.getEngine();
  60249. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  60250. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60251. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60252. return _this;
  60253. }
  60254. RawTexture.prototype.update = function (data) {
  60255. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  60256. };
  60257. // Statics
  60258. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60259. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60260. if (invertY === void 0) { invertY = false; }
  60261. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60262. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  60263. };
  60264. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60265. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60266. if (invertY === void 0) { invertY = false; }
  60267. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60268. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60269. };
  60270. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60271. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60272. if (invertY === void 0) { invertY = false; }
  60273. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60274. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60275. };
  60276. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60277. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60278. if (invertY === void 0) { invertY = false; }
  60279. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60280. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60281. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  60282. };
  60283. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60284. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60285. if (invertY === void 0) { invertY = false; }
  60286. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60287. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60288. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  60289. };
  60290. return RawTexture;
  60291. }(BABYLON.Texture));
  60292. BABYLON.RawTexture = RawTexture;
  60293. })(BABYLON || (BABYLON = {}));
  60294. //# sourceMappingURL=babylon.rawTexture.js.map
  60295. "use strict";
  60296. var BABYLON;
  60297. (function (BABYLON) {
  60298. /**
  60299. * PostProcess can be used to apply a shader to a texture after it has been rendered
  60300. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  60301. */
  60302. var PostProcess = /** @class */ (function () {
  60303. /**
  60304. * Creates a new instance of @see PostProcess
  60305. * @param name The name of the PostProcess.
  60306. * @param fragmentUrl The url of the fragment shader to be used.
  60307. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  60308. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  60309. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  60310. * @param camera The camera to apply the render pass to.
  60311. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  60312. * @param engine The engine which the post process will be applied. (default: current engine)
  60313. * @param reusable If the post process can be reused on the same frame. (default: false)
  60314. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  60315. * @param textureType Type of textures used when performing the post process. (default: 0)
  60316. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  60317. * @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
  60318. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  60319. */
  60320. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  60321. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  60322. if (defines === void 0) { defines = null; }
  60323. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60324. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  60325. if (blockCompilation === void 0) { blockCompilation = false; }
  60326. this.name = name;
  60327. /**
  60328. * Width of the texture to apply the post process on
  60329. */
  60330. this.width = -1;
  60331. /**
  60332. * Height of the texture to apply the post process on
  60333. */
  60334. this.height = -1;
  60335. /**
  60336. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  60337. */
  60338. this._outputTexture = null;
  60339. /**
  60340. * If the buffer needs to be cleared before applying the post process. (default: true)
  60341. * Should be set to false if shader will overwrite all previous pixels.
  60342. */
  60343. this.autoClear = true;
  60344. /**
  60345. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  60346. */
  60347. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  60348. /**
  60349. * Animations to be used for the post processing
  60350. */
  60351. this.animations = new Array();
  60352. /**
  60353. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  60354. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  60355. */
  60356. this.enablePixelPerfectMode = false;
  60357. /**
  60358. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  60359. */
  60360. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  60361. /**
  60362. * Force textures to be a power of two (default: false)
  60363. */
  60364. this.alwaysForcePOT = false;
  60365. /**
  60366. * Number of sample textures (default: 1)
  60367. */
  60368. this.samples = 1;
  60369. /**
  60370. * Modify the scale of the post process to be the same as the viewport (default: false)
  60371. */
  60372. this.adaptScaleToCurrentViewport = false;
  60373. this._reusable = false;
  60374. /**
  60375. * Smart array of input and output textures for the post process.
  60376. */
  60377. this._textures = new BABYLON.SmartArray(2);
  60378. /**
  60379. * The index in _textures that corresponds to the output texture.
  60380. */
  60381. this._currentRenderTextureInd = 0;
  60382. this._scaleRatio = new BABYLON.Vector2(1, 1);
  60383. this._texelSize = BABYLON.Vector2.Zero();
  60384. // Events
  60385. /**
  60386. * An event triggered when the postprocess is activated.
  60387. * @type {BABYLON.Observable}
  60388. */
  60389. this.onActivateObservable = new BABYLON.Observable();
  60390. /**
  60391. * An event triggered when the postprocess changes its size.
  60392. * @type {BABYLON.Observable}
  60393. */
  60394. this.onSizeChangedObservable = new BABYLON.Observable();
  60395. /**
  60396. * An event triggered when the postprocess applies its effect.
  60397. * @type {BABYLON.Observable}
  60398. */
  60399. this.onApplyObservable = new BABYLON.Observable();
  60400. /**
  60401. * An event triggered before rendering the postprocess
  60402. * @type {BABYLON.Observable}
  60403. */
  60404. this.onBeforeRenderObservable = new BABYLON.Observable();
  60405. /**
  60406. * An event triggered after rendering the postprocess
  60407. * @type {BABYLON.Observable}
  60408. */
  60409. this.onAfterRenderObservable = new BABYLON.Observable();
  60410. if (camera != null) {
  60411. this._camera = camera;
  60412. this._scene = camera.getScene();
  60413. camera.attachPostProcess(this);
  60414. this._engine = this._scene.getEngine();
  60415. this._scene.postProcesses.push(this);
  60416. }
  60417. else if (engine) {
  60418. this._engine = engine;
  60419. this._engine.postProcesses.push(this);
  60420. }
  60421. this._options = options;
  60422. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  60423. this._reusable = reusable || false;
  60424. this._textureType = textureType;
  60425. this._samplers = samplers || [];
  60426. this._samplers.push("textureSampler");
  60427. this._fragmentUrl = fragmentUrl;
  60428. this._vertexUrl = vertexUrl;
  60429. this._parameters = parameters || [];
  60430. this._parameters.push("scale");
  60431. this._indexParameters = indexParameters;
  60432. if (!blockCompilation) {
  60433. this.updateEffect(defines);
  60434. }
  60435. }
  60436. Object.defineProperty(PostProcess.prototype, "onActivate", {
  60437. /**
  60438. * A function that is added to the onActivateObservable
  60439. */
  60440. set: function (callback) {
  60441. if (this._onActivateObserver) {
  60442. this.onActivateObservable.remove(this._onActivateObserver);
  60443. }
  60444. if (callback) {
  60445. this._onActivateObserver = this.onActivateObservable.add(callback);
  60446. }
  60447. },
  60448. enumerable: true,
  60449. configurable: true
  60450. });
  60451. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  60452. /**
  60453. * A function that is added to the onSizeChangedObservable
  60454. */
  60455. set: function (callback) {
  60456. if (this._onSizeChangedObserver) {
  60457. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  60458. }
  60459. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  60460. },
  60461. enumerable: true,
  60462. configurable: true
  60463. });
  60464. Object.defineProperty(PostProcess.prototype, "onApply", {
  60465. /**
  60466. * A function that is added to the onApplyObservable
  60467. */
  60468. set: function (callback) {
  60469. if (this._onApplyObserver) {
  60470. this.onApplyObservable.remove(this._onApplyObserver);
  60471. }
  60472. this._onApplyObserver = this.onApplyObservable.add(callback);
  60473. },
  60474. enumerable: true,
  60475. configurable: true
  60476. });
  60477. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  60478. /**
  60479. * A function that is added to the onBeforeRenderObservable
  60480. */
  60481. set: function (callback) {
  60482. if (this._onBeforeRenderObserver) {
  60483. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  60484. }
  60485. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  60486. },
  60487. enumerable: true,
  60488. configurable: true
  60489. });
  60490. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  60491. /**
  60492. * A function that is added to the onAfterRenderObservable
  60493. */
  60494. set: function (callback) {
  60495. if (this._onAfterRenderObserver) {
  60496. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  60497. }
  60498. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  60499. },
  60500. enumerable: true,
  60501. configurable: true
  60502. });
  60503. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  60504. /**
  60505. * 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
  60506. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  60507. */
  60508. get: function () {
  60509. return this._textures.data[this._currentRenderTextureInd];
  60510. },
  60511. set: function (value) {
  60512. this._forcedOutputTexture = value;
  60513. },
  60514. enumerable: true,
  60515. configurable: true
  60516. });
  60517. /**
  60518. * Gets the camera which post process is applied to.
  60519. * @returns The camera the post process is applied to.
  60520. */
  60521. PostProcess.prototype.getCamera = function () {
  60522. return this._camera;
  60523. };
  60524. Object.defineProperty(PostProcess.prototype, "texelSize", {
  60525. /**
  60526. * Gets the texel size of the postprocess.
  60527. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  60528. */
  60529. get: function () {
  60530. if (this._shareOutputWithPostProcess) {
  60531. return this._shareOutputWithPostProcess.texelSize;
  60532. }
  60533. if (this._forcedOutputTexture) {
  60534. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  60535. }
  60536. return this._texelSize;
  60537. },
  60538. enumerable: true,
  60539. configurable: true
  60540. });
  60541. /**
  60542. * Gets the engine which this post process belongs to.
  60543. * @returns The engine the post process was enabled with.
  60544. */
  60545. PostProcess.prototype.getEngine = function () {
  60546. return this._engine;
  60547. };
  60548. /**
  60549. * The effect that is created when initializing the post process.
  60550. * @returns The created effect corrisponding the the postprocess.
  60551. */
  60552. PostProcess.prototype.getEffect = function () {
  60553. return this._effect;
  60554. };
  60555. /**
  60556. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  60557. * @param postProcess The post process to share the output with.
  60558. * @returns This post process.
  60559. */
  60560. PostProcess.prototype.shareOutputWith = function (postProcess) {
  60561. this._disposeTextures();
  60562. this._shareOutputWithPostProcess = postProcess;
  60563. return this;
  60564. };
  60565. /**
  60566. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  60567. * This should be called if the post process that shares output with this post process is disabled/disposed.
  60568. */
  60569. PostProcess.prototype.useOwnOutput = function () {
  60570. if (this._textures.length == 0) {
  60571. this._textures = new BABYLON.SmartArray(2);
  60572. }
  60573. this._shareOutputWithPostProcess = null;
  60574. };
  60575. /**
  60576. * Updates the effect with the current post process compile time values and recompiles the shader.
  60577. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  60578. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  60579. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  60580. * @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
  60581. * @param onCompiled Called when the shader has been compiled.
  60582. * @param onError Called if there is an error when compiling a shader.
  60583. */
  60584. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  60585. if (defines === void 0) { defines = null; }
  60586. if (uniforms === void 0) { uniforms = null; }
  60587. if (samplers === void 0) { samplers = null; }
  60588. 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);
  60589. };
  60590. /**
  60591. * The post process is reusable if it can be used multiple times within one frame.
  60592. * @returns If the post process is reusable
  60593. */
  60594. PostProcess.prototype.isReusable = function () {
  60595. return this._reusable;
  60596. };
  60597. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  60598. PostProcess.prototype.markTextureDirty = function () {
  60599. this.width = -1;
  60600. };
  60601. /**
  60602. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  60603. * 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.
  60604. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  60605. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  60606. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  60607. * @returns The target texture that was bound to be written to.
  60608. */
  60609. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  60610. var _this = this;
  60611. if (sourceTexture === void 0) { sourceTexture = null; }
  60612. camera = camera || this._camera;
  60613. var scene = camera.getScene();
  60614. var engine = scene.getEngine();
  60615. var maxSize = engine.getCaps().maxTextureSize;
  60616. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  60617. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  60618. // 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
  60619. var webVRCamera = camera.parent;
  60620. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  60621. requiredWidth /= 2;
  60622. }
  60623. var desiredWidth = (this._options.width || requiredWidth);
  60624. var desiredHeight = this._options.height || requiredHeight;
  60625. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  60626. if (this.adaptScaleToCurrentViewport) {
  60627. var currentViewport = engine.currentViewport;
  60628. if (currentViewport) {
  60629. desiredWidth *= currentViewport.width;
  60630. desiredHeight *= currentViewport.height;
  60631. }
  60632. }
  60633. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  60634. if (!this._options.width) {
  60635. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  60636. }
  60637. if (!this._options.height) {
  60638. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  60639. }
  60640. }
  60641. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  60642. if (this._textures.length > 0) {
  60643. for (var i = 0; i < this._textures.length; i++) {
  60644. this._engine._releaseTexture(this._textures.data[i]);
  60645. }
  60646. this._textures.reset();
  60647. }
  60648. this.width = desiredWidth;
  60649. this.height = desiredHeight;
  60650. var textureSize = { width: this.width, height: this.height };
  60651. var textureOptions = {
  60652. generateMipMaps: false,
  60653. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  60654. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  60655. samplingMode: this.renderTargetSamplingMode,
  60656. type: this._textureType
  60657. };
  60658. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60659. if (this._reusable) {
  60660. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60661. }
  60662. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  60663. this.onSizeChangedObservable.notifyObservers(this);
  60664. }
  60665. this._textures.forEach(function (texture) {
  60666. if (texture.samples !== _this.samples) {
  60667. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  60668. }
  60669. });
  60670. }
  60671. var target;
  60672. if (this._shareOutputWithPostProcess) {
  60673. target = this._shareOutputWithPostProcess.inputTexture;
  60674. }
  60675. else if (this._forcedOutputTexture) {
  60676. target = this._forcedOutputTexture;
  60677. this.width = this._forcedOutputTexture.width;
  60678. this.height = this._forcedOutputTexture.height;
  60679. }
  60680. else {
  60681. target = this.inputTexture;
  60682. }
  60683. // Bind the input of this post process to be used as the output of the previous post process.
  60684. if (this.enablePixelPerfectMode) {
  60685. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  60686. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  60687. }
  60688. else {
  60689. this._scaleRatio.copyFromFloats(1, 1);
  60690. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  60691. }
  60692. this.onActivateObservable.notifyObservers(camera);
  60693. // Clear
  60694. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  60695. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  60696. }
  60697. if (this._reusable) {
  60698. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  60699. }
  60700. return target;
  60701. };
  60702. Object.defineProperty(PostProcess.prototype, "isSupported", {
  60703. /**
  60704. * If the post process is supported.
  60705. */
  60706. get: function () {
  60707. return this._effect.isSupported;
  60708. },
  60709. enumerable: true,
  60710. configurable: true
  60711. });
  60712. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  60713. /**
  60714. * The aspect ratio of the output texture.
  60715. */
  60716. get: function () {
  60717. if (this._shareOutputWithPostProcess) {
  60718. return this._shareOutputWithPostProcess.aspectRatio;
  60719. }
  60720. if (this._forcedOutputTexture) {
  60721. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  60722. }
  60723. return this.width / this.height;
  60724. },
  60725. enumerable: true,
  60726. configurable: true
  60727. });
  60728. /**
  60729. * Get a value indicating if the post-process is ready to be used
  60730. * @returns true if the post-process is ready (shader is compiled)
  60731. */
  60732. PostProcess.prototype.isReady = function () {
  60733. return this._effect && this._effect.isReady();
  60734. };
  60735. /**
  60736. * Binds all textures and uniforms to the shader, this will be run on every pass.
  60737. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  60738. */
  60739. PostProcess.prototype.apply = function () {
  60740. // Check
  60741. if (!this._effect || !this._effect.isReady())
  60742. return null;
  60743. // States
  60744. this._engine.enableEffect(this._effect);
  60745. this._engine.setState(false);
  60746. this._engine.setDepthBuffer(false);
  60747. this._engine.setDepthWrite(false);
  60748. // Alpha
  60749. this._engine.setAlphaMode(this.alphaMode);
  60750. if (this.alphaConstants) {
  60751. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  60752. }
  60753. // Bind the output texture of the preivous post process as the input to this post process.
  60754. var source;
  60755. if (this._shareOutputWithPostProcess) {
  60756. source = this._shareOutputWithPostProcess.inputTexture;
  60757. }
  60758. else if (this._forcedOutputTexture) {
  60759. source = this._forcedOutputTexture;
  60760. }
  60761. else {
  60762. source = this.inputTexture;
  60763. }
  60764. this._effect._bindTexture("textureSampler", source);
  60765. // Parameters
  60766. this._effect.setVector2("scale", this._scaleRatio);
  60767. this.onApplyObservable.notifyObservers(this._effect);
  60768. return this._effect;
  60769. };
  60770. PostProcess.prototype._disposeTextures = function () {
  60771. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  60772. return;
  60773. }
  60774. if (this._textures.length > 0) {
  60775. for (var i = 0; i < this._textures.length; i++) {
  60776. this._engine._releaseTexture(this._textures.data[i]);
  60777. }
  60778. }
  60779. this._textures.dispose();
  60780. };
  60781. /**
  60782. * Disposes the post process.
  60783. * @param camera The camera to dispose the post process on.
  60784. */
  60785. PostProcess.prototype.dispose = function (camera) {
  60786. camera = camera || this._camera;
  60787. this._disposeTextures();
  60788. if (this._scene) {
  60789. var index_1 = this._scene.postProcesses.indexOf(this);
  60790. if (index_1 !== -1) {
  60791. this._scene.postProcesses.splice(index_1, 1);
  60792. }
  60793. }
  60794. else {
  60795. var index_2 = this._engine.postProcesses.indexOf(this);
  60796. if (index_2 !== -1) {
  60797. this._engine.postProcesses.splice(index_2, 1);
  60798. }
  60799. }
  60800. if (!camera) {
  60801. return;
  60802. }
  60803. camera.detachPostProcess(this);
  60804. var index = camera._postProcesses.indexOf(this);
  60805. if (index === 0 && camera._postProcesses.length > 0) {
  60806. var firstPostProcess = this._camera._getFirstPostProcess();
  60807. if (firstPostProcess) {
  60808. firstPostProcess.markTextureDirty();
  60809. }
  60810. }
  60811. this.onActivateObservable.clear();
  60812. this.onAfterRenderObservable.clear();
  60813. this.onApplyObservable.clear();
  60814. this.onBeforeRenderObservable.clear();
  60815. this.onSizeChangedObservable.clear();
  60816. };
  60817. return PostProcess;
  60818. }());
  60819. BABYLON.PostProcess = PostProcess;
  60820. })(BABYLON || (BABYLON = {}));
  60821. //# sourceMappingURL=babylon.postProcess.js.map
  60822. "use strict";
  60823. var BABYLON;
  60824. (function (BABYLON) {
  60825. var PassPostProcess = /** @class */ (function (_super) {
  60826. __extends(PassPostProcess, _super);
  60827. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  60828. if (camera === void 0) { camera = null; }
  60829. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60830. if (blockCompilation === void 0) { blockCompilation = false; }
  60831. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  60832. }
  60833. return PassPostProcess;
  60834. }(BABYLON.PostProcess));
  60835. BABYLON.PassPostProcess = PassPostProcess;
  60836. })(BABYLON || (BABYLON = {}));
  60837. //# sourceMappingURL=babylon.passPostProcess.js.map
  60838. "use strict";
  60839. var __assign = (this && this.__assign) || Object.assign || function(t) {
  60840. for (var s, i = 1, n = arguments.length; i < n; i++) {
  60841. s = arguments[i];
  60842. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  60843. t[p] = s[p];
  60844. }
  60845. return t;
  60846. };
  60847. var BABYLON;
  60848. (function (BABYLON) {
  60849. /**
  60850. * Default implementation of @see IShadowGenerator.
  60851. * This is the main object responsible of generating shadows in the framework.
  60852. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  60853. */
  60854. var ShadowGenerator = /** @class */ (function () {
  60855. /**
  60856. * Creates a ShadowGenerator object.
  60857. * A ShadowGenerator is the required tool to use the shadows.
  60858. * Each light casting shadows needs to use its own ShadowGenerator.
  60859. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  60860. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  60861. * @param light The light object generating the shadows.
  60862. * @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.
  60863. */
  60864. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  60865. this._bias = 0.00005;
  60866. this._normalBias = 0;
  60867. this._blurBoxOffset = 1;
  60868. this._blurScale = 2;
  60869. this._blurKernel = 1;
  60870. this._useKernelBlur = false;
  60871. this._filter = ShadowGenerator.FILTER_NONE;
  60872. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  60873. this._contactHardeningLightSizeUVRatio = 0.1;
  60874. this._darkness = 0;
  60875. this._transparencyShadow = false;
  60876. /**
  60877. * Controls the extent to which the shadows fade out at the edge of the frustum
  60878. * Used only by directionals and spots
  60879. */
  60880. this.frustumEdgeFalloff = 0;
  60881. /**
  60882. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  60883. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  60884. * It might on the other hand introduce peter panning.
  60885. */
  60886. this.forceBackFacesOnly = false;
  60887. this._lightDirection = BABYLON.Vector3.Zero();
  60888. this._viewMatrix = BABYLON.Matrix.Zero();
  60889. this._projectionMatrix = BABYLON.Matrix.Zero();
  60890. this._transformMatrix = BABYLON.Matrix.Zero();
  60891. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60892. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60893. this._currentFaceIndex = 0;
  60894. this._currentFaceIndexCache = 0;
  60895. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  60896. this._mapSize = mapSize;
  60897. this._light = light;
  60898. this._scene = light.getScene();
  60899. light._shadowGenerator = this;
  60900. // Texture type fallback from float to int if not supported.
  60901. var caps = this._scene.getEngine().getCaps();
  60902. if (!useFullFloatFirst) {
  60903. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60904. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60905. }
  60906. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60907. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60908. }
  60909. else {
  60910. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60911. }
  60912. }
  60913. else {
  60914. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60915. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60916. }
  60917. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60918. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60919. }
  60920. else {
  60921. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60922. }
  60923. }
  60924. this._initializeGenerator();
  60925. this._applyFilterValues();
  60926. }
  60927. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  60928. /**
  60929. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  60930. */
  60931. get: function () {
  60932. return this._bias;
  60933. },
  60934. /**
  60935. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  60936. */
  60937. set: function (bias) {
  60938. this._bias = bias;
  60939. },
  60940. enumerable: true,
  60941. configurable: true
  60942. });
  60943. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  60944. /**
  60945. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  60946. */
  60947. get: function () {
  60948. return this._normalBias;
  60949. },
  60950. /**
  60951. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  60952. */
  60953. set: function (normalBias) {
  60954. this._normalBias = normalBias;
  60955. },
  60956. enumerable: true,
  60957. configurable: true
  60958. });
  60959. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  60960. /**
  60961. * Gets the blur box offset: offset applied during the blur pass.
  60962. * Only usefull if useKernelBlur = false
  60963. */
  60964. get: function () {
  60965. return this._blurBoxOffset;
  60966. },
  60967. /**
  60968. * Sets the blur box offset: offset applied during the blur pass.
  60969. * Only usefull if useKernelBlur = false
  60970. */
  60971. set: function (value) {
  60972. if (this._blurBoxOffset === value) {
  60973. return;
  60974. }
  60975. this._blurBoxOffset = value;
  60976. this._disposeBlurPostProcesses();
  60977. },
  60978. enumerable: true,
  60979. configurable: true
  60980. });
  60981. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  60982. /**
  60983. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  60984. * 2 means half of the size.
  60985. */
  60986. get: function () {
  60987. return this._blurScale;
  60988. },
  60989. /**
  60990. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  60991. * 2 means half of the size.
  60992. */
  60993. set: function (value) {
  60994. if (this._blurScale === value) {
  60995. return;
  60996. }
  60997. this._blurScale = value;
  60998. this._disposeBlurPostProcesses();
  60999. },
  61000. enumerable: true,
  61001. configurable: true
  61002. });
  61003. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  61004. /**
  61005. * Gets the blur kernel: kernel size of the blur pass.
  61006. * Only usefull if useKernelBlur = true
  61007. */
  61008. get: function () {
  61009. return this._blurKernel;
  61010. },
  61011. /**
  61012. * Sets the blur kernel: kernel size of the blur pass.
  61013. * Only usefull if useKernelBlur = true
  61014. */
  61015. set: function (value) {
  61016. if (this._blurKernel === value) {
  61017. return;
  61018. }
  61019. this._blurKernel = value;
  61020. this._disposeBlurPostProcesses();
  61021. },
  61022. enumerable: true,
  61023. configurable: true
  61024. });
  61025. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  61026. /**
  61027. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  61028. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61029. */
  61030. get: function () {
  61031. return this._useKernelBlur;
  61032. },
  61033. /**
  61034. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  61035. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61036. */
  61037. set: function (value) {
  61038. if (this._useKernelBlur === value) {
  61039. return;
  61040. }
  61041. this._useKernelBlur = value;
  61042. this._disposeBlurPostProcesses();
  61043. },
  61044. enumerable: true,
  61045. configurable: true
  61046. });
  61047. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  61048. /**
  61049. * Gets the depth scale used in ESM mode.
  61050. */
  61051. get: function () {
  61052. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  61053. },
  61054. /**
  61055. * Sets the depth scale used in ESM mode.
  61056. * This can override the scale stored on the light.
  61057. */
  61058. set: function (value) {
  61059. this._depthScale = value;
  61060. },
  61061. enumerable: true,
  61062. configurable: true
  61063. });
  61064. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  61065. /**
  61066. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  61067. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61068. */
  61069. get: function () {
  61070. return this._filter;
  61071. },
  61072. /**
  61073. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  61074. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61075. */
  61076. set: function (value) {
  61077. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  61078. if (this._light.needCube()) {
  61079. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61080. this.useExponentialShadowMap = true;
  61081. return;
  61082. }
  61083. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61084. this.useCloseExponentialShadowMap = true;
  61085. return;
  61086. }
  61087. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61088. this.usePoissonSampling = true;
  61089. return;
  61090. }
  61091. }
  61092. // Weblg1 fallback for PCF.
  61093. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61094. if (this._scene.getEngine().webGLVersion === 1) {
  61095. this.usePoissonSampling = true;
  61096. return;
  61097. }
  61098. }
  61099. if (this._filter === value) {
  61100. return;
  61101. }
  61102. this._filter = value;
  61103. this._disposeBlurPostProcesses();
  61104. this._applyFilterValues();
  61105. this._light._markMeshesAsLightDirty();
  61106. },
  61107. enumerable: true,
  61108. configurable: true
  61109. });
  61110. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  61111. /**
  61112. * Gets if the current filter is set to Poisson Sampling.
  61113. */
  61114. get: function () {
  61115. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  61116. },
  61117. /**
  61118. * Sets the current filter to Poisson Sampling.
  61119. */
  61120. set: function (value) {
  61121. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  61122. return;
  61123. }
  61124. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  61125. },
  61126. enumerable: true,
  61127. configurable: true
  61128. });
  61129. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  61130. /**
  61131. * Gets if the current filter is set to VSM.
  61132. * DEPRECATED. Should use useExponentialShadowMap instead.
  61133. */
  61134. get: function () {
  61135. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61136. return this.useExponentialShadowMap;
  61137. },
  61138. /**
  61139. * Sets the current filter is to VSM.
  61140. * DEPRECATED. Should use useExponentialShadowMap instead.
  61141. */
  61142. set: function (value) {
  61143. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61144. this.useExponentialShadowMap = value;
  61145. },
  61146. enumerable: true,
  61147. configurable: true
  61148. });
  61149. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  61150. /**
  61151. * Gets if the current filter is set to blurred VSM.
  61152. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61153. */
  61154. get: function () {
  61155. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61156. return this.useBlurExponentialShadowMap;
  61157. },
  61158. /**
  61159. * Sets the current filter is to blurred VSM.
  61160. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61161. */
  61162. set: function (value) {
  61163. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61164. this.useBlurExponentialShadowMap = value;
  61165. },
  61166. enumerable: true,
  61167. configurable: true
  61168. });
  61169. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  61170. /**
  61171. * Gets if the current filter is set to ESM.
  61172. */
  61173. get: function () {
  61174. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  61175. },
  61176. /**
  61177. * Sets the current filter is to ESM.
  61178. */
  61179. set: function (value) {
  61180. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  61181. return;
  61182. }
  61183. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61184. },
  61185. enumerable: true,
  61186. configurable: true
  61187. });
  61188. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  61189. /**
  61190. * Gets if the current filter is set to filtered ESM.
  61191. */
  61192. get: function () {
  61193. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  61194. },
  61195. /**
  61196. * Gets if the current filter is set to filtered ESM.
  61197. */
  61198. set: function (value) {
  61199. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61200. return;
  61201. }
  61202. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61203. },
  61204. enumerable: true,
  61205. configurable: true
  61206. });
  61207. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  61208. /**
  61209. * Gets if the current filter is set to "close ESM" (using the inverse of the
  61210. * exponential to prevent steep falloff artifacts).
  61211. */
  61212. get: function () {
  61213. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  61214. },
  61215. /**
  61216. * Sets the current filter to "close ESM" (using the inverse of the
  61217. * exponential to prevent steep falloff artifacts).
  61218. */
  61219. set: function (value) {
  61220. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  61221. return;
  61222. }
  61223. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61224. },
  61225. enumerable: true,
  61226. configurable: true
  61227. });
  61228. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  61229. /**
  61230. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  61231. * exponential to prevent steep falloff artifacts).
  61232. */
  61233. get: function () {
  61234. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  61235. },
  61236. /**
  61237. * Sets the current filter to filtered "close ESM" (using the inverse of the
  61238. * exponential to prevent steep falloff artifacts).
  61239. */
  61240. set: function (value) {
  61241. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61242. return;
  61243. }
  61244. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61245. },
  61246. enumerable: true,
  61247. configurable: true
  61248. });
  61249. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  61250. /**
  61251. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  61252. */
  61253. get: function () {
  61254. return this.filter === ShadowGenerator.FILTER_PCF;
  61255. },
  61256. /**
  61257. * Sets the current filter to "PCF" (percentage closer filtering).
  61258. */
  61259. set: function (value) {
  61260. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  61261. return;
  61262. }
  61263. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  61264. },
  61265. enumerable: true,
  61266. configurable: true
  61267. });
  61268. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  61269. /**
  61270. * Gets the PCF or PCSS Quality.
  61271. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61272. */
  61273. get: function () {
  61274. return this._filteringQuality;
  61275. },
  61276. /**
  61277. * Sets the PCF or PCSS Quality.
  61278. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61279. */
  61280. set: function (filteringQuality) {
  61281. this._filteringQuality = filteringQuality;
  61282. },
  61283. enumerable: true,
  61284. configurable: true
  61285. });
  61286. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  61287. /**
  61288. * Gets if the current filter is set to "PCSS" (contact hardening).
  61289. */
  61290. get: function () {
  61291. return this.filter === ShadowGenerator.FILTER_PCSS;
  61292. },
  61293. /**
  61294. * Sets the current filter to "PCSS" (contact hardening).
  61295. */
  61296. set: function (value) {
  61297. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  61298. return;
  61299. }
  61300. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  61301. },
  61302. enumerable: true,
  61303. configurable: true
  61304. });
  61305. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  61306. /**
  61307. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61308. * Using a ratio helps keeping shape stability independently of the map size.
  61309. *
  61310. * It does not account for the light projection as it was having too much
  61311. * instability during the light setup or during light position changes.
  61312. *
  61313. * Only valid if useContactHardeningShadow is true.
  61314. */
  61315. get: function () {
  61316. return this._contactHardeningLightSizeUVRatio;
  61317. },
  61318. /**
  61319. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61320. * Using a ratio helps keeping shape stability independently of the map size.
  61321. *
  61322. * It does not account for the light projection as it was having too much
  61323. * instability during the light setup or during light position changes.
  61324. *
  61325. * Only valid if useContactHardeningShadow is true.
  61326. */
  61327. set: function (contactHardeningLightSizeUVRatio) {
  61328. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  61329. },
  61330. enumerable: true,
  61331. configurable: true
  61332. });
  61333. /**
  61334. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  61335. * 0 means strongest and 1 would means no shadow.
  61336. * @returns the darkness.
  61337. */
  61338. ShadowGenerator.prototype.getDarkness = function () {
  61339. return this._darkness;
  61340. };
  61341. /**
  61342. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  61343. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  61344. * @returns the shadow generator allowing fluent coding.
  61345. */
  61346. ShadowGenerator.prototype.setDarkness = function (darkness) {
  61347. if (darkness >= 1.0)
  61348. this._darkness = 1.0;
  61349. else if (darkness <= 0.0)
  61350. this._darkness = 0.0;
  61351. else
  61352. this._darkness = darkness;
  61353. return this;
  61354. };
  61355. /**
  61356. * Sets the ability to have transparent shadow (boolean).
  61357. * @param transparent True if transparent else False
  61358. * @returns the shadow generator allowing fluent coding
  61359. */
  61360. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  61361. this._transparencyShadow = transparent;
  61362. return this;
  61363. };
  61364. /**
  61365. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  61366. * @returns The render target texture if present otherwise, null
  61367. */
  61368. ShadowGenerator.prototype.getShadowMap = function () {
  61369. return this._shadowMap;
  61370. };
  61371. /**
  61372. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  61373. * @returns The render target texture if the shadow map is present otherwise, null
  61374. */
  61375. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  61376. if (this._shadowMap2) {
  61377. return this._shadowMap2;
  61378. }
  61379. return this._shadowMap;
  61380. };
  61381. /**
  61382. * Helper function to add a mesh and its descendants to the list of shadow casters.
  61383. * @param mesh Mesh to add
  61384. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  61385. * @returns the Shadow Generator itself
  61386. */
  61387. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  61388. if (includeDescendants === void 0) { includeDescendants = true; }
  61389. if (!this._shadowMap) {
  61390. return this;
  61391. }
  61392. if (!this._shadowMap.renderList) {
  61393. this._shadowMap.renderList = [];
  61394. }
  61395. this._shadowMap.renderList.push(mesh);
  61396. if (includeDescendants) {
  61397. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  61398. }
  61399. return this;
  61400. var _a;
  61401. };
  61402. /**
  61403. * Helper function to remove a mesh and its descendants from the list of shadow casters
  61404. * @param mesh Mesh to remove
  61405. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  61406. * @returns the Shadow Generator itself
  61407. */
  61408. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  61409. if (includeDescendants === void 0) { includeDescendants = true; }
  61410. if (!this._shadowMap || !this._shadowMap.renderList) {
  61411. return this;
  61412. }
  61413. var index = this._shadowMap.renderList.indexOf(mesh);
  61414. if (index !== -1) {
  61415. this._shadowMap.renderList.splice(index, 1);
  61416. }
  61417. if (includeDescendants) {
  61418. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  61419. var child = _a[_i];
  61420. this.removeShadowCaster(child);
  61421. }
  61422. }
  61423. return this;
  61424. };
  61425. /**
  61426. * Returns the associated light object.
  61427. * @returns the light generating the shadow
  61428. */
  61429. ShadowGenerator.prototype.getLight = function () {
  61430. return this._light;
  61431. };
  61432. ShadowGenerator.prototype._initializeGenerator = function () {
  61433. this._light._markMeshesAsLightDirty();
  61434. this._initializeShadowMap();
  61435. };
  61436. ShadowGenerator.prototype._initializeShadowMap = function () {
  61437. var _this = this;
  61438. // Render target
  61439. var engine = this._scene.getEngine();
  61440. if (engine.webGLVersion > 1) {
  61441. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  61442. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  61443. }
  61444. else {
  61445. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  61446. }
  61447. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61448. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61449. this._shadowMap.anisotropicFilteringLevel = 1;
  61450. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61451. this._shadowMap.renderParticles = false;
  61452. this._shadowMap.ignoreCameraViewport = true;
  61453. // Record Face Index before render.
  61454. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  61455. _this._currentFaceIndex = faceIndex;
  61456. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61457. engine.setColorWrite(false);
  61458. }
  61459. });
  61460. // Custom render function.
  61461. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  61462. // Blur if required afer render.
  61463. this._shadowMap.onAfterUnbindObservable.add(function () {
  61464. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61465. engine.setColorWrite(true);
  61466. }
  61467. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  61468. return;
  61469. }
  61470. var shadowMap = _this.getShadowMapForRendering();
  61471. if (shadowMap) {
  61472. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  61473. }
  61474. });
  61475. // Clear according to the chosen filter.
  61476. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  61477. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61478. this._shadowMap.onClearObservable.add(function (engine) {
  61479. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61480. engine.clear(clearOne, false, true, false);
  61481. }
  61482. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  61483. engine.clear(clearZero, true, true, false);
  61484. }
  61485. else {
  61486. engine.clear(clearOne, true, true, false);
  61487. }
  61488. });
  61489. };
  61490. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  61491. var _this = this;
  61492. var engine = this._scene.getEngine();
  61493. var targetSize = this._mapSize / this.blurScale;
  61494. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  61495. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  61496. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61497. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61498. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61499. }
  61500. if (this.useKernelBlur) {
  61501. 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);
  61502. this._kernelBlurXPostprocess.width = targetSize;
  61503. this._kernelBlurXPostprocess.height = targetSize;
  61504. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  61505. effect.setTexture("textureSampler", _this._shadowMap);
  61506. });
  61507. 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);
  61508. this._kernelBlurXPostprocess.autoClear = false;
  61509. this._kernelBlurYPostprocess.autoClear = false;
  61510. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61511. this._kernelBlurXPostprocess.packedFloat = true;
  61512. this._kernelBlurYPostprocess.packedFloat = true;
  61513. }
  61514. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  61515. }
  61516. else {
  61517. 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);
  61518. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  61519. effect.setFloat2("screenSize", targetSize, targetSize);
  61520. effect.setTexture("textureSampler", _this._shadowMap);
  61521. });
  61522. this._boxBlurPostprocess.autoClear = false;
  61523. this._blurPostProcesses = [this._boxBlurPostprocess];
  61524. }
  61525. };
  61526. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61527. var index;
  61528. var engine = this._scene.getEngine();
  61529. if (depthOnlySubMeshes.length) {
  61530. engine.setColorWrite(false);
  61531. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61532. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  61533. }
  61534. engine.setColorWrite(true);
  61535. }
  61536. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61537. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  61538. }
  61539. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61540. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  61541. }
  61542. if (this._transparencyShadow) {
  61543. for (index = 0; index < transparentSubMeshes.length; index++) {
  61544. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  61545. }
  61546. }
  61547. };
  61548. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  61549. var _this = this;
  61550. var mesh = subMesh.getRenderingMesh();
  61551. var scene = this._scene;
  61552. var engine = scene.getEngine();
  61553. var material = subMesh.getMaterial();
  61554. if (!material) {
  61555. return;
  61556. }
  61557. // Culling
  61558. engine.setState(material.backFaceCulling);
  61559. // Managing instances
  61560. var batch = mesh._getInstancesRenderList(subMesh._id);
  61561. if (batch.mustReturn) {
  61562. return;
  61563. }
  61564. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  61565. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  61566. engine.enableEffect(this._effect);
  61567. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  61568. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  61569. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  61570. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61571. this._effect.setVector3("lightData", this._cachedDirection);
  61572. }
  61573. else {
  61574. this._effect.setVector3("lightData", this._cachedPosition);
  61575. }
  61576. if (scene.activeCamera) {
  61577. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  61578. }
  61579. // Alpha test
  61580. if (material && material.needAlphaTesting()) {
  61581. var alphaTexture = material.getAlphaTestTexture();
  61582. if (alphaTexture) {
  61583. this._effect.setTexture("diffuseSampler", alphaTexture);
  61584. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  61585. }
  61586. }
  61587. // Bones
  61588. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61589. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  61590. }
  61591. if (this.forceBackFacesOnly) {
  61592. engine.setState(true, 0, false, true);
  61593. }
  61594. // Draw
  61595. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61596. if (this.forceBackFacesOnly) {
  61597. engine.setState(true, 0, false, false);
  61598. }
  61599. }
  61600. else {
  61601. // Need to reset refresh rate of the shadowMap
  61602. if (this._shadowMap) {
  61603. this._shadowMap.resetRefreshCounter();
  61604. }
  61605. }
  61606. };
  61607. ShadowGenerator.prototype._applyFilterValues = function () {
  61608. if (!this._shadowMap) {
  61609. return;
  61610. }
  61611. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  61612. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61613. }
  61614. else {
  61615. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61616. }
  61617. };
  61618. /**
  61619. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61620. * @param onCompiled Callback triggered at the and of the effects compilation
  61621. * @param options Sets of optional options forcing the compilation with different modes
  61622. */
  61623. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  61624. var _this = this;
  61625. var localOptions = __assign({ useInstances: false }, options);
  61626. var shadowMap = this.getShadowMap();
  61627. if (!shadowMap) {
  61628. if (onCompiled) {
  61629. onCompiled(this);
  61630. }
  61631. return;
  61632. }
  61633. var renderList = shadowMap.renderList;
  61634. if (!renderList) {
  61635. if (onCompiled) {
  61636. onCompiled(this);
  61637. }
  61638. return;
  61639. }
  61640. var subMeshes = new Array();
  61641. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  61642. var mesh = renderList_1[_i];
  61643. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  61644. }
  61645. if (subMeshes.length === 0) {
  61646. if (onCompiled) {
  61647. onCompiled(this);
  61648. }
  61649. return;
  61650. }
  61651. var currentIndex = 0;
  61652. var checkReady = function () {
  61653. if (!_this._scene || !_this._scene.getEngine()) {
  61654. return;
  61655. }
  61656. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  61657. currentIndex++;
  61658. if (currentIndex >= subMeshes.length) {
  61659. if (onCompiled) {
  61660. onCompiled(_this);
  61661. }
  61662. return;
  61663. }
  61664. }
  61665. setTimeout(checkReady, 16);
  61666. };
  61667. checkReady();
  61668. };
  61669. /**
  61670. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61671. * @param options Sets of optional options forcing the compilation with different modes
  61672. * @returns A promise that resolves when the compilation completes
  61673. */
  61674. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  61675. var _this = this;
  61676. return new Promise(function (resolve) {
  61677. _this.forceCompilation(function () {
  61678. resolve();
  61679. }, options);
  61680. });
  61681. };
  61682. /**
  61683. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  61684. * @param subMesh The submesh we want to render in the shadow map
  61685. * @param useInstances Defines wether will draw in the map using instances
  61686. * @returns true if ready otherwise, false
  61687. */
  61688. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  61689. var defines = [];
  61690. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61691. defines.push("#define FLOAT");
  61692. }
  61693. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61694. defines.push("#define ESM");
  61695. }
  61696. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  61697. defines.push("#define DEPTHTEXTURE");
  61698. }
  61699. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61700. var mesh = subMesh.getMesh();
  61701. var material = subMesh.getMaterial();
  61702. // Normal bias.
  61703. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  61704. attribs.push(BABYLON.VertexBuffer.NormalKind);
  61705. defines.push("#define NORMAL");
  61706. if (mesh.nonUniformScaling) {
  61707. defines.push("#define NONUNIFORMSCALING");
  61708. }
  61709. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61710. defines.push("#define DIRECTIONINLIGHTDATA");
  61711. }
  61712. }
  61713. // Alpha test
  61714. if (material && material.needAlphaTesting()) {
  61715. var alphaTexture = material.getAlphaTestTexture();
  61716. if (alphaTexture) {
  61717. defines.push("#define ALPHATEST");
  61718. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61719. attribs.push(BABYLON.VertexBuffer.UVKind);
  61720. defines.push("#define UV1");
  61721. }
  61722. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61723. if (alphaTexture.coordinatesIndex === 1) {
  61724. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61725. defines.push("#define UV2");
  61726. }
  61727. }
  61728. }
  61729. }
  61730. // Bones
  61731. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61732. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61733. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61734. if (mesh.numBoneInfluencers > 4) {
  61735. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61736. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61737. }
  61738. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61739. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61740. }
  61741. else {
  61742. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61743. }
  61744. // Instances
  61745. if (useInstances) {
  61746. defines.push("#define INSTANCES");
  61747. attribs.push("world0");
  61748. attribs.push("world1");
  61749. attribs.push("world2");
  61750. attribs.push("world3");
  61751. }
  61752. // Get correct effect
  61753. var join = defines.join("\n");
  61754. if (this._cachedDefines !== join) {
  61755. this._cachedDefines = join;
  61756. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  61757. }
  61758. if (!this._effect.isReady()) {
  61759. return false;
  61760. }
  61761. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61762. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  61763. this._initializeBlurRTTAndPostProcesses();
  61764. }
  61765. }
  61766. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  61767. return false;
  61768. }
  61769. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  61770. return false;
  61771. }
  61772. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  61773. return false;
  61774. }
  61775. return true;
  61776. };
  61777. /**
  61778. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  61779. * @param defines Defines of the material we want to update
  61780. * @param lightIndex Index of the light in the enabled light list of the material
  61781. */
  61782. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  61783. var scene = this._scene;
  61784. var light = this._light;
  61785. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61786. return;
  61787. }
  61788. defines["SHADOW" + lightIndex] = true;
  61789. if (this.useContactHardeningShadow) {
  61790. defines["SHADOWPCSS" + lightIndex] = true;
  61791. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61792. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61793. }
  61794. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61795. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61796. }
  61797. // else default to high.
  61798. }
  61799. if (this.usePercentageCloserFiltering) {
  61800. defines["SHADOWPCF" + lightIndex] = true;
  61801. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61802. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61803. }
  61804. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61805. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61806. }
  61807. // else default to high.
  61808. }
  61809. else if (this.usePoissonSampling) {
  61810. defines["SHADOWPOISSON" + lightIndex] = true;
  61811. }
  61812. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61813. defines["SHADOWESM" + lightIndex] = true;
  61814. }
  61815. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61816. defines["SHADOWCLOSEESM" + lightIndex] = true;
  61817. }
  61818. if (light.needCube()) {
  61819. defines["SHADOWCUBE" + lightIndex] = true;
  61820. }
  61821. };
  61822. /**
  61823. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  61824. * defined in the generator but impacting the effect).
  61825. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  61826. * @param effect The effect we are binfing the information for
  61827. */
  61828. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  61829. var light = this._light;
  61830. var scene = this._scene;
  61831. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61832. return;
  61833. }
  61834. var camera = scene.activeCamera;
  61835. if (!camera) {
  61836. return;
  61837. }
  61838. var shadowMap = this.getShadowMap();
  61839. if (!shadowMap) {
  61840. return;
  61841. }
  61842. if (!light.needCube()) {
  61843. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  61844. }
  61845. // Only PCF uses depth stencil texture.
  61846. if (this._filter === ShadowGenerator.FILTER_PCF) {
  61847. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61848. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  61849. }
  61850. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  61851. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61852. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  61853. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  61854. }
  61855. else {
  61856. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61857. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  61858. }
  61859. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  61860. };
  61861. /**
  61862. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  61863. * (eq to shadow prjection matrix * light transform matrix)
  61864. * @returns The transform matrix used to create the shadow map
  61865. */
  61866. ShadowGenerator.prototype.getTransformMatrix = function () {
  61867. var scene = this._scene;
  61868. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  61869. return this._transformMatrix;
  61870. }
  61871. this._currentRenderID = scene.getRenderId();
  61872. this._currentFaceIndexCache = this._currentFaceIndex;
  61873. var lightPosition = this._light.position;
  61874. if (this._light.computeTransformedInformation()) {
  61875. lightPosition = this._light.transformedPosition;
  61876. }
  61877. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  61878. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  61879. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  61880. }
  61881. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  61882. this._cachedPosition.copyFrom(lightPosition);
  61883. this._cachedDirection.copyFrom(this._lightDirection);
  61884. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  61885. var shadowMap = this.getShadowMap();
  61886. if (shadowMap) {
  61887. var renderList = shadowMap.renderList;
  61888. if (renderList) {
  61889. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  61890. }
  61891. }
  61892. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  61893. }
  61894. return this._transformMatrix;
  61895. };
  61896. /**
  61897. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  61898. * Cube and 2D textures for instance.
  61899. */
  61900. ShadowGenerator.prototype.recreateShadowMap = function () {
  61901. var shadowMap = this._shadowMap;
  61902. if (!shadowMap) {
  61903. return;
  61904. }
  61905. // Track render list.
  61906. var renderList = shadowMap.renderList;
  61907. // Clean up existing data.
  61908. this._disposeRTTandPostProcesses();
  61909. // Reinitializes.
  61910. this._initializeGenerator();
  61911. // Reaffect the filter to ensure a correct fallback if necessary.
  61912. this.filter = this.filter;
  61913. // Reaffect the filter.
  61914. this._applyFilterValues();
  61915. // Reaffect Render List.
  61916. this._shadowMap.renderList = renderList;
  61917. };
  61918. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  61919. if (this._shadowMap2) {
  61920. this._shadowMap2.dispose();
  61921. this._shadowMap2 = null;
  61922. }
  61923. if (this._boxBlurPostprocess) {
  61924. this._boxBlurPostprocess.dispose();
  61925. this._boxBlurPostprocess = null;
  61926. }
  61927. if (this._kernelBlurXPostprocess) {
  61928. this._kernelBlurXPostprocess.dispose();
  61929. this._kernelBlurXPostprocess = null;
  61930. }
  61931. if (this._kernelBlurYPostprocess) {
  61932. this._kernelBlurYPostprocess.dispose();
  61933. this._kernelBlurYPostprocess = null;
  61934. }
  61935. this._blurPostProcesses = [];
  61936. };
  61937. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  61938. if (this._shadowMap) {
  61939. this._shadowMap.dispose();
  61940. this._shadowMap = null;
  61941. }
  61942. this._disposeBlurPostProcesses();
  61943. };
  61944. /**
  61945. * Disposes the ShadowGenerator.
  61946. * Returns nothing.
  61947. */
  61948. ShadowGenerator.prototype.dispose = function () {
  61949. this._disposeRTTandPostProcesses();
  61950. if (this._light) {
  61951. this._light._shadowGenerator = null;
  61952. this._light._markMeshesAsLightDirty();
  61953. }
  61954. };
  61955. /**
  61956. * Serializes the shadow generator setup to a json object.
  61957. * @returns The serialized JSON object
  61958. */
  61959. ShadowGenerator.prototype.serialize = function () {
  61960. var serializationObject = {};
  61961. var shadowMap = this.getShadowMap();
  61962. if (!shadowMap) {
  61963. return serializationObject;
  61964. }
  61965. serializationObject.lightId = this._light.id;
  61966. serializationObject.mapSize = shadowMap.getRenderSize();
  61967. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  61968. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  61969. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61970. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61971. serializationObject.usePoissonSampling = this.usePoissonSampling;
  61972. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  61973. serializationObject.depthScale = this.depthScale;
  61974. serializationObject.darkness = this.getDarkness();
  61975. serializationObject.blurBoxOffset = this.blurBoxOffset;
  61976. serializationObject.blurKernel = this.blurKernel;
  61977. serializationObject.blurScale = this.blurScale;
  61978. serializationObject.useKernelBlur = this.useKernelBlur;
  61979. serializationObject.transparencyShadow = this._transparencyShadow;
  61980. serializationObject.bias = this.bias;
  61981. serializationObject.normalBias = this.normalBias;
  61982. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  61983. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  61984. serializationObject.filteringQuality = this.filteringQuality;
  61985. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  61986. serializationObject.renderList = [];
  61987. if (shadowMap.renderList) {
  61988. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  61989. var mesh = shadowMap.renderList[meshIndex];
  61990. serializationObject.renderList.push(mesh.id);
  61991. }
  61992. }
  61993. return serializationObject;
  61994. };
  61995. /**
  61996. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  61997. * @param parsedShadowGenerator The JSON object to parse
  61998. * @param scene The scene to create the shadow map for
  61999. * @returns The parsed shadow generator
  62000. */
  62001. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  62002. //casting to point light, as light is missing the position attr and typescript complains.
  62003. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  62004. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  62005. var shadowMap = shadowGenerator.getShadowMap();
  62006. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  62007. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  62008. meshes.forEach(function (mesh) {
  62009. if (!shadowMap) {
  62010. return;
  62011. }
  62012. if (!shadowMap.renderList) {
  62013. shadowMap.renderList = [];
  62014. }
  62015. shadowMap.renderList.push(mesh);
  62016. });
  62017. }
  62018. if (parsedShadowGenerator.usePoissonSampling) {
  62019. shadowGenerator.usePoissonSampling = true;
  62020. }
  62021. else if (parsedShadowGenerator.useExponentialShadowMap) {
  62022. shadowGenerator.useExponentialShadowMap = true;
  62023. }
  62024. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  62025. shadowGenerator.useBlurExponentialShadowMap = true;
  62026. }
  62027. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  62028. shadowGenerator.useCloseExponentialShadowMap = true;
  62029. }
  62030. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  62031. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  62032. }
  62033. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  62034. shadowGenerator.usePercentageCloserFiltering = true;
  62035. }
  62036. else if (parsedShadowGenerator.useContactHardeningShadow) {
  62037. shadowGenerator.useContactHardeningShadow = true;
  62038. }
  62039. if (parsedShadowGenerator.filteringQuality) {
  62040. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  62041. }
  62042. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  62043. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  62044. }
  62045. else if (parsedShadowGenerator.useVarianceShadowMap) {
  62046. shadowGenerator.useExponentialShadowMap = true;
  62047. }
  62048. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  62049. shadowGenerator.useBlurExponentialShadowMap = true;
  62050. }
  62051. if (parsedShadowGenerator.depthScale) {
  62052. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  62053. }
  62054. if (parsedShadowGenerator.blurScale) {
  62055. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  62056. }
  62057. if (parsedShadowGenerator.blurBoxOffset) {
  62058. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  62059. }
  62060. if (parsedShadowGenerator.useKernelBlur) {
  62061. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  62062. }
  62063. if (parsedShadowGenerator.blurKernel) {
  62064. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  62065. }
  62066. if (parsedShadowGenerator.bias !== undefined) {
  62067. shadowGenerator.bias = parsedShadowGenerator.bias;
  62068. }
  62069. if (parsedShadowGenerator.normalBias !== undefined) {
  62070. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  62071. }
  62072. if (parsedShadowGenerator.darkness) {
  62073. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  62074. }
  62075. if (parsedShadowGenerator.transparencyShadow) {
  62076. shadowGenerator.setTransparencyShadow(true);
  62077. }
  62078. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  62079. return shadowGenerator;
  62080. };
  62081. /**
  62082. * Shadow generator mode None: no filtering applied.
  62083. */
  62084. ShadowGenerator.FILTER_NONE = 0;
  62085. /**
  62086. * Shadow generator mode ESM: Exponential Shadow Mapping.
  62087. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62088. */
  62089. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  62090. /**
  62091. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  62092. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  62093. */
  62094. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  62095. /**
  62096. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  62097. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62098. */
  62099. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  62100. /**
  62101. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  62102. * edge artifacts on steep falloff.
  62103. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62104. */
  62105. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  62106. /**
  62107. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  62108. * edge artifacts on steep falloff.
  62109. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62110. */
  62111. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  62112. /**
  62113. * Shadow generator mode PCF: Percentage Closer Filtering
  62114. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62115. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  62116. */
  62117. ShadowGenerator.FILTER_PCF = 6;
  62118. /**
  62119. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  62120. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62121. * Contact Hardening
  62122. */
  62123. ShadowGenerator.FILTER_PCSS = 7;
  62124. /**
  62125. * Reserved for PCF and PCSS
  62126. * Highest Quality.
  62127. *
  62128. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  62129. *
  62130. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  62131. */
  62132. ShadowGenerator.QUALITY_HIGH = 0;
  62133. /**
  62134. * Reserved for PCF and PCSS
  62135. * Good tradeoff for quality/perf cross devices
  62136. *
  62137. * Execute PCF on a 3*3 kernel.
  62138. *
  62139. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  62140. */
  62141. ShadowGenerator.QUALITY_MEDIUM = 1;
  62142. /**
  62143. * Reserved for PCF and PCSS
  62144. * The lowest quality but the fastest.
  62145. *
  62146. * Execute PCF on a 1*1 kernel.
  62147. *
  62148. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  62149. */
  62150. ShadowGenerator.QUALITY_LOW = 2;
  62151. return ShadowGenerator;
  62152. }());
  62153. BABYLON.ShadowGenerator = ShadowGenerator;
  62154. })(BABYLON || (BABYLON = {}));
  62155. //# sourceMappingURL=babylon.shadowGenerator.js.map
  62156. "use strict";
  62157. var BABYLON;
  62158. (function (BABYLON) {
  62159. var DefaultLoadingScreen = /** @class */ (function () {
  62160. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  62161. if (_loadingText === void 0) { _loadingText = ""; }
  62162. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  62163. var _this = this;
  62164. this._renderingCanvas = _renderingCanvas;
  62165. this._loadingText = _loadingText;
  62166. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  62167. // Resize
  62168. this._resizeLoadingUI = function () {
  62169. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  62170. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  62171. if (!_this._loadingDiv) {
  62172. return;
  62173. }
  62174. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  62175. _this._loadingDiv.style.left = canvasRect.left + "px";
  62176. _this._loadingDiv.style.top = canvasRect.top + "px";
  62177. _this._loadingDiv.style.width = canvasRect.width + "px";
  62178. _this._loadingDiv.style.height = canvasRect.height + "px";
  62179. };
  62180. }
  62181. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  62182. if (this._loadingDiv) {
  62183. // Do not add a loading screen if there is already one
  62184. return;
  62185. }
  62186. this._loadingDiv = document.createElement("div");
  62187. this._loadingDiv.id = "babylonjsLoadingDiv";
  62188. this._loadingDiv.style.opacity = "0";
  62189. this._loadingDiv.style.transition = "opacity 1.5s ease";
  62190. this._loadingDiv.style.pointerEvents = "none";
  62191. // Loading text
  62192. this._loadingTextDiv = document.createElement("div");
  62193. this._loadingTextDiv.style.position = "absolute";
  62194. this._loadingTextDiv.style.left = "0";
  62195. this._loadingTextDiv.style.top = "50%";
  62196. this._loadingTextDiv.style.marginTop = "80px";
  62197. this._loadingTextDiv.style.width = "100%";
  62198. this._loadingTextDiv.style.height = "20px";
  62199. this._loadingTextDiv.style.fontFamily = "Arial";
  62200. this._loadingTextDiv.style.fontSize = "14px";
  62201. this._loadingTextDiv.style.color = "white";
  62202. this._loadingTextDiv.style.textAlign = "center";
  62203. this._loadingTextDiv.innerHTML = "Loading";
  62204. this._loadingDiv.appendChild(this._loadingTextDiv);
  62205. //set the predefined text
  62206. this._loadingTextDiv.innerHTML = this._loadingText;
  62207. // Generating keyframes
  62208. var style = document.createElement('style');
  62209. style.type = 'text/css';
  62210. 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 }";
  62211. style.innerHTML = keyFrames;
  62212. document.getElementsByTagName('head')[0].appendChild(style);
  62213. // Loading img
  62214. var imgBack = new Image();
  62215. 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";
  62216. imgBack.style.position = "absolute";
  62217. imgBack.style.left = "50%";
  62218. imgBack.style.top = "50%";
  62219. imgBack.style.marginLeft = "-60px";
  62220. imgBack.style.marginTop = "-60px";
  62221. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  62222. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  62223. imgBack.style.transformOrigin = "50% 50%";
  62224. imgBack.style.webkitTransformOrigin = "50% 50%";
  62225. this._loadingDiv.appendChild(imgBack);
  62226. this._resizeLoadingUI();
  62227. window.addEventListener("resize", this._resizeLoadingUI);
  62228. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62229. document.body.appendChild(this._loadingDiv);
  62230. this._loadingDiv.style.opacity = "1";
  62231. };
  62232. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  62233. var _this = this;
  62234. if (!this._loadingDiv) {
  62235. return;
  62236. }
  62237. var onTransitionEnd = function () {
  62238. if (!_this._loadingDiv) {
  62239. return;
  62240. }
  62241. document.body.removeChild(_this._loadingDiv);
  62242. window.removeEventListener("resize", _this._resizeLoadingUI);
  62243. _this._loadingDiv = null;
  62244. };
  62245. this._loadingDiv.style.opacity = "0";
  62246. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  62247. };
  62248. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  62249. set: function (text) {
  62250. this._loadingText = text;
  62251. if (this._loadingTextDiv) {
  62252. this._loadingTextDiv.innerHTML = this._loadingText;
  62253. }
  62254. },
  62255. enumerable: true,
  62256. configurable: true
  62257. });
  62258. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  62259. get: function () {
  62260. return this._loadingDivBackgroundColor;
  62261. },
  62262. set: function (color) {
  62263. this._loadingDivBackgroundColor = color;
  62264. if (!this._loadingDiv) {
  62265. return;
  62266. }
  62267. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62268. },
  62269. enumerable: true,
  62270. configurable: true
  62271. });
  62272. return DefaultLoadingScreen;
  62273. }());
  62274. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  62275. })(BABYLON || (BABYLON = {}));
  62276. //# sourceMappingURL=babylon.loadingScreen.js.map
  62277. "use strict";
  62278. var BABYLON;
  62279. (function (BABYLON) {
  62280. var SceneLoaderProgressEvent = /** @class */ (function () {
  62281. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  62282. this.lengthComputable = lengthComputable;
  62283. this.loaded = loaded;
  62284. this.total = total;
  62285. }
  62286. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  62287. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  62288. };
  62289. return SceneLoaderProgressEvent;
  62290. }());
  62291. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  62292. var SceneLoader = /** @class */ (function () {
  62293. function SceneLoader() {
  62294. }
  62295. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  62296. get: function () {
  62297. return 0;
  62298. },
  62299. enumerable: true,
  62300. configurable: true
  62301. });
  62302. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  62303. get: function () {
  62304. return 1;
  62305. },
  62306. enumerable: true,
  62307. configurable: true
  62308. });
  62309. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  62310. get: function () {
  62311. return 2;
  62312. },
  62313. enumerable: true,
  62314. configurable: true
  62315. });
  62316. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  62317. get: function () {
  62318. return 3;
  62319. },
  62320. enumerable: true,
  62321. configurable: true
  62322. });
  62323. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  62324. get: function () {
  62325. return SceneLoader._ForceFullSceneLoadingForIncremental;
  62326. },
  62327. set: function (value) {
  62328. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  62329. },
  62330. enumerable: true,
  62331. configurable: true
  62332. });
  62333. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  62334. get: function () {
  62335. return SceneLoader._ShowLoadingScreen;
  62336. },
  62337. set: function (value) {
  62338. SceneLoader._ShowLoadingScreen = value;
  62339. },
  62340. enumerable: true,
  62341. configurable: true
  62342. });
  62343. Object.defineProperty(SceneLoader, "loggingLevel", {
  62344. get: function () {
  62345. return SceneLoader._loggingLevel;
  62346. },
  62347. set: function (value) {
  62348. SceneLoader._loggingLevel = value;
  62349. },
  62350. enumerable: true,
  62351. configurable: true
  62352. });
  62353. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  62354. get: function () {
  62355. return SceneLoader._CleanBoneMatrixWeights;
  62356. },
  62357. set: function (value) {
  62358. SceneLoader._CleanBoneMatrixWeights = value;
  62359. },
  62360. enumerable: true,
  62361. configurable: true
  62362. });
  62363. SceneLoader._getDefaultPlugin = function () {
  62364. return SceneLoader._registeredPlugins[".babylon"];
  62365. };
  62366. SceneLoader._getPluginForExtension = function (extension) {
  62367. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  62368. if (registeredPlugin) {
  62369. return registeredPlugin;
  62370. }
  62371. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  62372. return SceneLoader._getDefaultPlugin();
  62373. };
  62374. SceneLoader._getPluginForDirectLoad = function (data) {
  62375. for (var extension in SceneLoader._registeredPlugins) {
  62376. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  62377. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  62378. return SceneLoader._registeredPlugins[extension];
  62379. }
  62380. }
  62381. return SceneLoader._getDefaultPlugin();
  62382. };
  62383. SceneLoader._getPluginForFilename = function (sceneFilename) {
  62384. if (sceneFilename.name) {
  62385. sceneFilename = sceneFilename.name;
  62386. }
  62387. var queryStringPosition = sceneFilename.indexOf("?");
  62388. if (queryStringPosition !== -1) {
  62389. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  62390. }
  62391. var dotPosition = sceneFilename.lastIndexOf(".");
  62392. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  62393. return SceneLoader._getPluginForExtension(extension);
  62394. };
  62395. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  62396. SceneLoader._getDirectLoad = function (sceneFilename) {
  62397. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  62398. return sceneFilename.substr(5);
  62399. }
  62400. return null;
  62401. };
  62402. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  62403. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  62404. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  62405. var plugin;
  62406. if (registeredPlugin.plugin.createPlugin) {
  62407. plugin = registeredPlugin.plugin.createPlugin();
  62408. }
  62409. else {
  62410. plugin = registeredPlugin.plugin;
  62411. }
  62412. var useArrayBuffer = registeredPlugin.isBinary;
  62413. var database;
  62414. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  62415. var dataCallback = function (data, responseURL) {
  62416. if (scene.isDisposed) {
  62417. onError("Scene has been disposed");
  62418. return;
  62419. }
  62420. scene.database = database;
  62421. onSuccess(plugin, data, responseURL);
  62422. };
  62423. var request = null;
  62424. var pluginDisposed = false;
  62425. var onDisposeObservable = plugin.onDisposeObservable;
  62426. if (onDisposeObservable) {
  62427. onDisposeObservable.add(function () {
  62428. pluginDisposed = true;
  62429. if (request) {
  62430. request.abort();
  62431. request = null;
  62432. }
  62433. onDispose();
  62434. });
  62435. }
  62436. var manifestChecked = function () {
  62437. if (pluginDisposed) {
  62438. return;
  62439. }
  62440. var url = rootUrl + sceneFilename;
  62441. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  62442. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  62443. } : undefined, database, useArrayBuffer, function (request, exception) {
  62444. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  62445. });
  62446. };
  62447. if (directLoad) {
  62448. dataCallback(directLoad);
  62449. return plugin;
  62450. }
  62451. if (rootUrl.indexOf("file:") === -1) {
  62452. if (scene.getEngine().enableOfflineSupport) {
  62453. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  62454. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  62455. }
  62456. else {
  62457. manifestChecked();
  62458. }
  62459. }
  62460. else {
  62461. var fileOrString = sceneFilename;
  62462. if (fileOrString.name) {
  62463. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  62464. }
  62465. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  62466. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  62467. }
  62468. else {
  62469. onError("Unable to find file named " + sceneFilename);
  62470. }
  62471. }
  62472. return plugin;
  62473. };
  62474. // Public functions
  62475. SceneLoader.GetPluginForExtension = function (extension) {
  62476. return SceneLoader._getPluginForExtension(extension).plugin;
  62477. };
  62478. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  62479. return !!SceneLoader._registeredPlugins[extension];
  62480. };
  62481. SceneLoader.RegisterPlugin = function (plugin) {
  62482. if (typeof plugin.extensions === "string") {
  62483. var extension = plugin.extensions;
  62484. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62485. plugin: plugin,
  62486. isBinary: false
  62487. };
  62488. }
  62489. else {
  62490. var extensions = plugin.extensions;
  62491. Object.keys(extensions).forEach(function (extension) {
  62492. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62493. plugin: plugin,
  62494. isBinary: extensions[extension].isBinary
  62495. };
  62496. });
  62497. }
  62498. };
  62499. /**
  62500. * Import meshes into a scene
  62501. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62502. * @param rootUrl a string that defines the root url for scene and resources
  62503. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62504. * @param scene the instance of BABYLON.Scene to append to
  62505. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  62506. * @param onProgress a callback with a progress event for each file being loaded
  62507. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62508. * @param pluginExtension the extension used to determine the plugin
  62509. * @returns The loaded plugin
  62510. */
  62511. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62512. if (onSuccess === void 0) { onSuccess = null; }
  62513. if (onProgress === void 0) { onProgress = null; }
  62514. if (onError === void 0) { onError = null; }
  62515. if (pluginExtension === void 0) { pluginExtension = null; }
  62516. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62517. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62518. return null;
  62519. }
  62520. var loadingToken = {};
  62521. scene._addPendingData(loadingToken);
  62522. var disposeHandler = function () {
  62523. scene._removePendingData(loadingToken);
  62524. };
  62525. var errorHandler = function (message, exception) {
  62526. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  62527. if (onError) {
  62528. onError(scene, errorMessage, exception);
  62529. }
  62530. else {
  62531. BABYLON.Tools.Error(errorMessage);
  62532. // should the exception be thrown?
  62533. }
  62534. disposeHandler();
  62535. };
  62536. var progressHandler = onProgress ? function (event) {
  62537. try {
  62538. onProgress(event);
  62539. }
  62540. catch (e) {
  62541. errorHandler("Error in onProgress callback", e);
  62542. }
  62543. } : undefined;
  62544. var successHandler = function (meshes, particleSystems, skeletons) {
  62545. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  62546. if (onSuccess) {
  62547. try {
  62548. onSuccess(meshes, particleSystems, skeletons);
  62549. }
  62550. catch (e) {
  62551. errorHandler("Error in onSuccess callback", e);
  62552. }
  62553. }
  62554. scene._removePendingData(loadingToken);
  62555. };
  62556. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62557. if (plugin.rewriteRootURL) {
  62558. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  62559. }
  62560. if (sceneFilename === "") {
  62561. if (sceneFilename === "") {
  62562. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62563. }
  62564. }
  62565. if (plugin.importMesh) {
  62566. var syncedPlugin = plugin;
  62567. var meshes = new Array();
  62568. var particleSystems = new Array();
  62569. var skeletons = new Array();
  62570. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  62571. return;
  62572. }
  62573. scene.loadingPluginName = plugin.name;
  62574. successHandler(meshes, particleSystems, skeletons);
  62575. }
  62576. else {
  62577. var asyncedPlugin = plugin;
  62578. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  62579. scene.loadingPluginName = plugin.name;
  62580. successHandler(result.meshes, result.particleSystems, result.skeletons);
  62581. }).catch(function (error) {
  62582. errorHandler(error.message, error);
  62583. });
  62584. }
  62585. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62586. };
  62587. /**
  62588. * Import meshes into a scene
  62589. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62590. * @param rootUrl a string that defines the root url for scene and resources
  62591. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62592. * @param scene the instance of BABYLON.Scene to append to
  62593. * @param onProgress a callback with a progress event for each file being loaded
  62594. * @param pluginExtension the extension used to determine the plugin
  62595. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  62596. */
  62597. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62598. if (onProgress === void 0) { onProgress = null; }
  62599. if (pluginExtension === void 0) { pluginExtension = null; }
  62600. return new Promise(function (resolve, reject) {
  62601. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  62602. resolve({
  62603. meshes: meshes,
  62604. particleSystems: particleSystems,
  62605. skeletons: skeletons
  62606. });
  62607. }, onProgress, function (scene, message, exception) {
  62608. reject(exception || new Error(message));
  62609. });
  62610. });
  62611. };
  62612. /**
  62613. * Load a scene
  62614. * @param rootUrl a string that defines the root url for scene and resources
  62615. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62616. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62617. * @param onSuccess a callback with the scene when import succeeds
  62618. * @param onProgress a callback with a progress event for each file being loaded
  62619. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62620. * @param pluginExtension the extension used to determine the plugin
  62621. * @returns The loaded plugin
  62622. */
  62623. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  62624. if (onSuccess === void 0) { onSuccess = null; }
  62625. if (onProgress === void 0) { onProgress = null; }
  62626. if (onError === void 0) { onError = null; }
  62627. if (pluginExtension === void 0) { pluginExtension = null; }
  62628. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  62629. };
  62630. /**
  62631. * Load a scene
  62632. * @param rootUrl a string that defines the root url for scene and resources
  62633. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62634. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62635. * @param onProgress a callback with a progress event for each file being loaded
  62636. * @param pluginExtension the extension used to determine the plugin
  62637. * @returns The loaded scene
  62638. */
  62639. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  62640. if (onProgress === void 0) { onProgress = null; }
  62641. if (pluginExtension === void 0) { pluginExtension = null; }
  62642. return new Promise(function (resolve, reject) {
  62643. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  62644. resolve(scene);
  62645. }, onProgress, function (scene, message, exception) {
  62646. reject(exception || new Error(message));
  62647. }, pluginExtension);
  62648. });
  62649. };
  62650. /**
  62651. * Append a scene
  62652. * @param rootUrl a string that defines the root url for scene and resources
  62653. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62654. * @param scene is the instance of BABYLON.Scene to append to
  62655. * @param onSuccess a callback with the scene when import succeeds
  62656. * @param onProgress a callback with a progress event for each file being loaded
  62657. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62658. * @param pluginExtension the extension used to determine the plugin
  62659. * @returns The loaded plugin
  62660. */
  62661. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62662. if (onSuccess === void 0) { onSuccess = null; }
  62663. if (onProgress === void 0) { onProgress = null; }
  62664. if (onError === void 0) { onError = null; }
  62665. if (pluginExtension === void 0) { pluginExtension = null; }
  62666. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62667. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62668. return null;
  62669. }
  62670. if (SceneLoader.ShowLoadingScreen) {
  62671. scene.getEngine().displayLoadingUI();
  62672. }
  62673. var loadingToken = {};
  62674. scene._addPendingData(loadingToken);
  62675. var disposeHandler = function () {
  62676. scene._removePendingData(loadingToken);
  62677. scene.getEngine().hideLoadingUI();
  62678. };
  62679. var errorHandler = function (message, exception) {
  62680. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62681. if (onError) {
  62682. onError(scene, errorMessage, exception);
  62683. }
  62684. else {
  62685. BABYLON.Tools.Error(errorMessage);
  62686. // should the exception be thrown?
  62687. }
  62688. disposeHandler();
  62689. };
  62690. var progressHandler = onProgress ? function (event) {
  62691. try {
  62692. onProgress(event);
  62693. }
  62694. catch (e) {
  62695. errorHandler("Error in onProgress callback", e);
  62696. }
  62697. } : undefined;
  62698. var successHandler = function () {
  62699. if (onSuccess) {
  62700. try {
  62701. onSuccess(scene);
  62702. }
  62703. catch (e) {
  62704. errorHandler("Error in onSuccess callback", e);
  62705. }
  62706. }
  62707. scene._removePendingData(loadingToken);
  62708. };
  62709. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62710. if (sceneFilename === "") {
  62711. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62712. }
  62713. if (plugin.load) {
  62714. var syncedPlugin = plugin;
  62715. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  62716. return;
  62717. }
  62718. scene.loadingPluginName = plugin.name;
  62719. successHandler();
  62720. }
  62721. else {
  62722. var asyncedPlugin = plugin;
  62723. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  62724. scene.loadingPluginName = plugin.name;
  62725. successHandler();
  62726. }).catch(function (error) {
  62727. errorHandler(error.message, error);
  62728. });
  62729. }
  62730. if (SceneLoader.ShowLoadingScreen) {
  62731. scene.executeWhenReady(function () {
  62732. scene.getEngine().hideLoadingUI();
  62733. });
  62734. }
  62735. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62736. };
  62737. /**
  62738. * Append a scene
  62739. * @param rootUrl a string that defines the root url for scene and resources
  62740. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62741. * @param scene is the instance of BABYLON.Scene to append to
  62742. * @param onProgress a callback with a progress event for each file being loaded
  62743. * @param pluginExtension the extension used to determine the plugin
  62744. * @returns The given scene
  62745. */
  62746. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62747. if (onProgress === void 0) { onProgress = null; }
  62748. if (pluginExtension === void 0) { pluginExtension = null; }
  62749. return new Promise(function (resolve, reject) {
  62750. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  62751. resolve(scene);
  62752. }, onProgress, function (scene, message, exception) {
  62753. reject(exception || new Error(message));
  62754. }, pluginExtension);
  62755. });
  62756. };
  62757. /**
  62758. * Load a scene into an asset container
  62759. * @param rootUrl a string that defines the root url for scene and resources
  62760. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62761. * @param scene is the instance of BABYLON.Scene to append to
  62762. * @param onSuccess a callback with the scene when import succeeds
  62763. * @param onProgress a callback with a progress event for each file being loaded
  62764. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62765. * @param pluginExtension the extension used to determine the plugin
  62766. * @returns The loaded plugin
  62767. */
  62768. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62769. if (onSuccess === void 0) { onSuccess = null; }
  62770. if (onProgress === void 0) { onProgress = null; }
  62771. if (onError === void 0) { onError = null; }
  62772. if (pluginExtension === void 0) { pluginExtension = null; }
  62773. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62774. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62775. return null;
  62776. }
  62777. var loadingToken = {};
  62778. scene._addPendingData(loadingToken);
  62779. var disposeHandler = function () {
  62780. scene._removePendingData(loadingToken);
  62781. };
  62782. var errorHandler = function (message, exception) {
  62783. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62784. if (onError) {
  62785. onError(scene, errorMessage, exception);
  62786. }
  62787. else {
  62788. BABYLON.Tools.Error(errorMessage);
  62789. // should the exception be thrown?
  62790. }
  62791. disposeHandler();
  62792. };
  62793. var progressHandler = onProgress ? function (event) {
  62794. try {
  62795. onProgress(event);
  62796. }
  62797. catch (e) {
  62798. errorHandler("Error in onProgress callback", e);
  62799. }
  62800. } : undefined;
  62801. var successHandler = function (assets) {
  62802. if (onSuccess) {
  62803. try {
  62804. onSuccess(assets);
  62805. }
  62806. catch (e) {
  62807. errorHandler("Error in onSuccess callback", e);
  62808. }
  62809. }
  62810. scene._removePendingData(loadingToken);
  62811. };
  62812. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62813. if (plugin.loadAssetContainer) {
  62814. var syncedPlugin = plugin;
  62815. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  62816. if (!assetContainer) {
  62817. return;
  62818. }
  62819. scene.loadingPluginName = plugin.name;
  62820. successHandler(assetContainer);
  62821. }
  62822. else if (plugin.loadAssetContainerAsync) {
  62823. var asyncedPlugin = plugin;
  62824. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  62825. scene.loadingPluginName = plugin.name;
  62826. successHandler(assetContainer);
  62827. }).catch(function (error) {
  62828. errorHandler(error.message, error);
  62829. });
  62830. }
  62831. else {
  62832. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  62833. }
  62834. if (SceneLoader.ShowLoadingScreen) {
  62835. scene.executeWhenReady(function () {
  62836. scene.getEngine().hideLoadingUI();
  62837. });
  62838. }
  62839. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62840. };
  62841. /**
  62842. * Load a scene into an asset container
  62843. * @param rootUrl a string that defines the root url for scene and resources
  62844. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62845. * @param scene is the instance of BABYLON.Scene to append to
  62846. * @param onProgress a callback with a progress event for each file being loaded
  62847. * @param pluginExtension the extension used to determine the plugin
  62848. * @returns The loaded asset container
  62849. */
  62850. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62851. if (onProgress === void 0) { onProgress = null; }
  62852. if (pluginExtension === void 0) { pluginExtension = null; }
  62853. return new Promise(function (resolve, reject) {
  62854. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  62855. resolve(assetContainer);
  62856. }, onProgress, function (scene, message, exception) {
  62857. reject(exception || new Error(message));
  62858. }, pluginExtension);
  62859. });
  62860. };
  62861. // Flags
  62862. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  62863. SceneLoader._ShowLoadingScreen = true;
  62864. SceneLoader._CleanBoneMatrixWeights = false;
  62865. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  62866. // Members
  62867. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  62868. SceneLoader._registeredPlugins = {};
  62869. return SceneLoader;
  62870. }());
  62871. BABYLON.SceneLoader = SceneLoader;
  62872. ;
  62873. })(BABYLON || (BABYLON = {}));
  62874. //# sourceMappingURL=babylon.sceneLoader.js.map
  62875. "use strict";
  62876. var BABYLON;
  62877. (function (BABYLON) {
  62878. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  62879. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62880. var parsedMaterial = parsedData.materials[index];
  62881. if (parsedMaterial.id === id) {
  62882. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62883. }
  62884. }
  62885. return null;
  62886. };
  62887. var isDescendantOf = function (mesh, names, hierarchyIds) {
  62888. for (var i in names) {
  62889. if (mesh.name === names[i]) {
  62890. hierarchyIds.push(mesh.id);
  62891. return true;
  62892. }
  62893. }
  62894. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  62895. hierarchyIds.push(mesh.id);
  62896. return true;
  62897. }
  62898. return false;
  62899. };
  62900. var logOperation = function (operation, producer) {
  62901. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  62902. };
  62903. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  62904. if (addToScene === void 0) { addToScene = false; }
  62905. var container = new BABYLON.AssetContainer(scene);
  62906. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62907. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62908. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62909. // and avoid problems with multiple concurrent .babylon loads.
  62910. var log = "importScene has failed JSON parse";
  62911. try {
  62912. var parsedData = JSON.parse(data);
  62913. log = "";
  62914. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62915. var index;
  62916. var cache;
  62917. // Lights
  62918. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  62919. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  62920. var parsedLight = parsedData.lights[index];
  62921. var light = BABYLON.Light.Parse(parsedLight, scene);
  62922. if (light) {
  62923. container.lights.push(light);
  62924. log += (index === 0 ? "\n\tLights:" : "");
  62925. log += "\n\t\t" + light.toString(fullDetails);
  62926. }
  62927. }
  62928. }
  62929. // Animations
  62930. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  62931. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  62932. var parsedAnimation = parsedData.animations[index];
  62933. var animation = BABYLON.Animation.Parse(parsedAnimation);
  62934. scene.animations.push(animation);
  62935. container.animations.push(animation);
  62936. log += (index === 0 ? "\n\tAnimations:" : "");
  62937. log += "\n\t\t" + animation.toString(fullDetails);
  62938. }
  62939. }
  62940. // Materials
  62941. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  62942. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62943. var parsedMaterial = parsedData.materials[index];
  62944. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62945. container.materials.push(mat);
  62946. log += (index === 0 ? "\n\tMaterials:" : "");
  62947. log += "\n\t\t" + mat.toString(fullDetails);
  62948. }
  62949. }
  62950. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62951. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  62952. var parsedMultiMaterial = parsedData.multiMaterials[index];
  62953. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62954. container.multiMaterials.push(mmat);
  62955. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  62956. log += "\n\t\t" + mmat.toString(fullDetails);
  62957. }
  62958. }
  62959. // Morph targets
  62960. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  62961. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  62962. var managerData = _a[_i];
  62963. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  62964. }
  62965. }
  62966. // Skeletons
  62967. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62968. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  62969. var parsedSkeleton = parsedData.skeletons[index];
  62970. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62971. container.skeletons.push(skeleton);
  62972. log += (index === 0 ? "\n\tSkeletons:" : "");
  62973. log += "\n\t\t" + skeleton.toString(fullDetails);
  62974. }
  62975. }
  62976. // Geometries
  62977. var geometries = parsedData.geometries;
  62978. if (geometries !== undefined && geometries !== null) {
  62979. var addedGeometry = new Array();
  62980. // Boxes
  62981. var boxes = geometries.boxes;
  62982. if (boxes !== undefined && boxes !== null) {
  62983. for (index = 0, cache = boxes.length; index < cache; index++) {
  62984. var parsedBox = boxes[index];
  62985. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  62986. }
  62987. }
  62988. // Spheres
  62989. var spheres = geometries.spheres;
  62990. if (spheres !== undefined && spheres !== null) {
  62991. for (index = 0, cache = spheres.length; index < cache; index++) {
  62992. var parsedSphere = spheres[index];
  62993. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  62994. }
  62995. }
  62996. // Cylinders
  62997. var cylinders = geometries.cylinders;
  62998. if (cylinders !== undefined && cylinders !== null) {
  62999. for (index = 0, cache = cylinders.length; index < cache; index++) {
  63000. var parsedCylinder = cylinders[index];
  63001. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  63002. }
  63003. }
  63004. // Toruses
  63005. var toruses = geometries.toruses;
  63006. if (toruses !== undefined && toruses !== null) {
  63007. for (index = 0, cache = toruses.length; index < cache; index++) {
  63008. var parsedTorus = toruses[index];
  63009. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  63010. }
  63011. }
  63012. // Grounds
  63013. var grounds = geometries.grounds;
  63014. if (grounds !== undefined && grounds !== null) {
  63015. for (index = 0, cache = grounds.length; index < cache; index++) {
  63016. var parsedGround = grounds[index];
  63017. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  63018. }
  63019. }
  63020. // Planes
  63021. var planes = geometries.planes;
  63022. if (planes !== undefined && planes !== null) {
  63023. for (index = 0, cache = planes.length; index < cache; index++) {
  63024. var parsedPlane = planes[index];
  63025. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  63026. }
  63027. }
  63028. // TorusKnots
  63029. var torusKnots = geometries.torusKnots;
  63030. if (torusKnots !== undefined && torusKnots !== null) {
  63031. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  63032. var parsedTorusKnot = torusKnots[index];
  63033. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  63034. }
  63035. }
  63036. // VertexData
  63037. var vertexData = geometries.vertexData;
  63038. if (vertexData !== undefined && vertexData !== null) {
  63039. for (index = 0, cache = vertexData.length; index < cache; index++) {
  63040. var parsedVertexData = vertexData[index];
  63041. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  63042. }
  63043. }
  63044. addedGeometry.forEach(function (g) {
  63045. if (g) {
  63046. container.geometries.push(g);
  63047. }
  63048. });
  63049. }
  63050. // Transform nodes
  63051. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  63052. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  63053. var parsedTransformNode = parsedData.transformNodes[index];
  63054. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  63055. container.transformNodes.push(node);
  63056. }
  63057. }
  63058. // Meshes
  63059. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63060. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63061. var parsedMesh = parsedData.meshes[index];
  63062. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63063. container.meshes.push(mesh);
  63064. log += (index === 0 ? "\n\tMeshes:" : "");
  63065. log += "\n\t\t" + mesh.toString(fullDetails);
  63066. }
  63067. }
  63068. // Cameras
  63069. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  63070. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  63071. var parsedCamera = parsedData.cameras[index];
  63072. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  63073. container.cameras.push(camera);
  63074. log += (index === 0 ? "\n\tCameras:" : "");
  63075. log += "\n\t\t" + camera.toString(fullDetails);
  63076. }
  63077. }
  63078. // Browsing all the graph to connect the dots
  63079. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  63080. var camera = scene.cameras[index];
  63081. if (camera._waitingParentId) {
  63082. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  63083. camera._waitingParentId = null;
  63084. }
  63085. }
  63086. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63087. var light_1 = scene.lights[index];
  63088. if (light_1 && light_1._waitingParentId) {
  63089. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  63090. light_1._waitingParentId = null;
  63091. }
  63092. }
  63093. // Sounds
  63094. // TODO: add sound
  63095. var loadedSounds = [];
  63096. var loadedSound;
  63097. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  63098. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  63099. var parsedSound = parsedData.sounds[index];
  63100. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63101. if (!parsedSound.url)
  63102. parsedSound.url = parsedSound.name;
  63103. if (!loadedSounds[parsedSound.url]) {
  63104. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  63105. loadedSounds[parsedSound.url] = loadedSound;
  63106. container.sounds.push(loadedSound);
  63107. }
  63108. else {
  63109. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  63110. }
  63111. }
  63112. else {
  63113. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  63114. }
  63115. }
  63116. }
  63117. loadedSounds = [];
  63118. // Connect parents & children and parse actions
  63119. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  63120. var transformNode = scene.transformNodes[index];
  63121. if (transformNode._waitingParentId) {
  63122. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  63123. transformNode._waitingParentId = null;
  63124. }
  63125. }
  63126. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63127. var mesh = scene.meshes[index];
  63128. if (mesh._waitingParentId) {
  63129. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  63130. mesh._waitingParentId = null;
  63131. }
  63132. if (mesh._waitingActions) {
  63133. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  63134. mesh._waitingActions = null;
  63135. }
  63136. }
  63137. // freeze world matrix application
  63138. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63139. var currentMesh = scene.meshes[index];
  63140. if (currentMesh._waitingFreezeWorldMatrix) {
  63141. currentMesh.freezeWorldMatrix();
  63142. currentMesh._waitingFreezeWorldMatrix = null;
  63143. }
  63144. else {
  63145. currentMesh.computeWorldMatrix(true);
  63146. }
  63147. }
  63148. // Particles Systems
  63149. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63150. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63151. var parsedParticleSystem = parsedData.particleSystems[index];
  63152. if (parsedParticleSystem.activeParticleCount) {
  63153. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63154. container.particleSystems.push(ps);
  63155. }
  63156. else {
  63157. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63158. container.particleSystems.push(ps);
  63159. }
  63160. }
  63161. }
  63162. // Lens flares
  63163. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  63164. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  63165. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  63166. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  63167. container.lensFlareSystems.push(lf);
  63168. }
  63169. }
  63170. // Shadows
  63171. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  63172. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  63173. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  63174. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  63175. container.shadowGenerators.push(sg);
  63176. }
  63177. }
  63178. // Lights exclusions / inclusions
  63179. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63180. var light_2 = scene.lights[index];
  63181. // Excluded check
  63182. if (light_2._excludedMeshesIds.length > 0) {
  63183. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  63184. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  63185. if (excludedMesh) {
  63186. light_2.excludedMeshes.push(excludedMesh);
  63187. }
  63188. }
  63189. light_2._excludedMeshesIds = [];
  63190. }
  63191. // Included check
  63192. if (light_2._includedOnlyMeshesIds.length > 0) {
  63193. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  63194. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  63195. if (includedOnlyMesh) {
  63196. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  63197. }
  63198. }
  63199. light_2._includedOnlyMeshesIds = [];
  63200. }
  63201. }
  63202. // Actions (scene)
  63203. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  63204. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  63205. }
  63206. if (!addToScene) {
  63207. container.removeAllFromScene();
  63208. }
  63209. }
  63210. catch (err) {
  63211. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  63212. if (onError) {
  63213. onError(msg, err);
  63214. }
  63215. else {
  63216. BABYLON.Tools.Log(msg);
  63217. throw err;
  63218. }
  63219. }
  63220. finally {
  63221. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63222. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63223. }
  63224. }
  63225. return container;
  63226. };
  63227. BABYLON.SceneLoader.RegisterPlugin({
  63228. name: "babylon.js",
  63229. extensions: ".babylon",
  63230. canDirectLoad: function (data) {
  63231. if (data.indexOf("babylon") !== -1) {
  63232. return true;
  63233. }
  63234. return false;
  63235. },
  63236. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  63237. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63238. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63239. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63240. // and avoid problems with multiple concurrent .babylon loads.
  63241. var log = "importMesh has failed JSON parse";
  63242. try {
  63243. var parsedData = JSON.parse(data);
  63244. log = "";
  63245. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63246. if (!meshesNames) {
  63247. meshesNames = null;
  63248. }
  63249. else if (!Array.isArray(meshesNames)) {
  63250. meshesNames = [meshesNames];
  63251. }
  63252. var hierarchyIds = new Array();
  63253. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63254. var loadedSkeletonsIds = [];
  63255. var loadedMaterialsIds = [];
  63256. var index;
  63257. var cache;
  63258. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63259. var parsedMesh = parsedData.meshes[index];
  63260. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  63261. if (meshesNames !== null) {
  63262. // Remove found mesh name from list.
  63263. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  63264. }
  63265. //Geometry?
  63266. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  63267. //does the file contain geometries?
  63268. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  63269. //find the correct geometry and add it to the scene
  63270. var found = false;
  63271. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  63272. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  63273. return;
  63274. }
  63275. else {
  63276. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  63277. if (parsedGeometryData.id === parsedMesh.geometryId) {
  63278. switch (geometryType) {
  63279. case "boxes":
  63280. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  63281. break;
  63282. case "spheres":
  63283. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  63284. break;
  63285. case "cylinders":
  63286. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  63287. break;
  63288. case "toruses":
  63289. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  63290. break;
  63291. case "grounds":
  63292. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  63293. break;
  63294. case "planes":
  63295. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  63296. break;
  63297. case "torusKnots":
  63298. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  63299. break;
  63300. case "vertexData":
  63301. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  63302. break;
  63303. }
  63304. found = true;
  63305. }
  63306. });
  63307. }
  63308. });
  63309. if (found === false) {
  63310. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  63311. }
  63312. }
  63313. }
  63314. // Material ?
  63315. if (parsedMesh.materialId) {
  63316. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  63317. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63318. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  63319. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  63320. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  63321. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  63322. var subMatId = parsedMultiMaterial.materials[matIndex];
  63323. loadedMaterialsIds.push(subMatId);
  63324. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  63325. if (mat) {
  63326. log += "\n\tMaterial " + mat.toString(fullDetails);
  63327. }
  63328. }
  63329. loadedMaterialsIds.push(parsedMultiMaterial.id);
  63330. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63331. if (mmat) {
  63332. materialFound = true;
  63333. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  63334. }
  63335. break;
  63336. }
  63337. }
  63338. }
  63339. if (materialFound === false) {
  63340. loadedMaterialsIds.push(parsedMesh.materialId);
  63341. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  63342. if (!mat) {
  63343. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  63344. }
  63345. else {
  63346. log += "\n\tMaterial " + mat.toString(fullDetails);
  63347. }
  63348. }
  63349. }
  63350. // Skeleton ?
  63351. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63352. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  63353. if (skeletonAlreadyLoaded === false) {
  63354. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  63355. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  63356. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  63357. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63358. skeletons.push(skeleton);
  63359. loadedSkeletonsIds.push(parsedSkeleton.id);
  63360. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  63361. }
  63362. }
  63363. }
  63364. }
  63365. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63366. meshes.push(mesh);
  63367. log += "\n\tMesh " + mesh.toString(fullDetails);
  63368. }
  63369. }
  63370. // Connecting parents
  63371. var currentMesh;
  63372. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63373. currentMesh = scene.meshes[index];
  63374. if (currentMesh._waitingParentId) {
  63375. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  63376. currentMesh._waitingParentId = null;
  63377. }
  63378. }
  63379. // freeze and compute world matrix application
  63380. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63381. currentMesh = scene.meshes[index];
  63382. if (currentMesh._waitingFreezeWorldMatrix) {
  63383. currentMesh.freezeWorldMatrix();
  63384. currentMesh._waitingFreezeWorldMatrix = null;
  63385. }
  63386. else {
  63387. currentMesh.computeWorldMatrix(true);
  63388. }
  63389. }
  63390. }
  63391. // Particles
  63392. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63393. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63394. var parsedParticleSystem = parsedData.particleSystems[index];
  63395. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  63396. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  63397. }
  63398. }
  63399. }
  63400. return true;
  63401. }
  63402. catch (err) {
  63403. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  63404. if (onError) {
  63405. onError(msg, err);
  63406. }
  63407. else {
  63408. BABYLON.Tools.Log(msg);
  63409. throw err;
  63410. }
  63411. }
  63412. finally {
  63413. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63414. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63415. }
  63416. }
  63417. return false;
  63418. },
  63419. load: function (scene, data, rootUrl, onError) {
  63420. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63421. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63422. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63423. // and avoid problems with multiple concurrent .babylon loads.
  63424. var log = "importScene has failed JSON parse";
  63425. try {
  63426. var parsedData = JSON.parse(data);
  63427. log = "";
  63428. // Scene
  63429. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  63430. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  63431. }
  63432. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  63433. scene.autoClear = parsedData.autoClear;
  63434. }
  63435. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  63436. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  63437. }
  63438. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  63439. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  63440. }
  63441. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  63442. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  63443. }
  63444. // Fog
  63445. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  63446. scene.fogMode = parsedData.fogMode;
  63447. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  63448. scene.fogStart = parsedData.fogStart;
  63449. scene.fogEnd = parsedData.fogEnd;
  63450. scene.fogDensity = parsedData.fogDensity;
  63451. log += "\tFog mode for scene: ";
  63452. switch (scene.fogMode) {
  63453. // getters not compiling, so using hardcoded
  63454. case 1:
  63455. log += "exp\n";
  63456. break;
  63457. case 2:
  63458. log += "exp2\n";
  63459. break;
  63460. case 3:
  63461. log += "linear\n";
  63462. break;
  63463. }
  63464. }
  63465. //Physics
  63466. if (parsedData.physicsEnabled) {
  63467. var physicsPlugin;
  63468. if (parsedData.physicsEngine === "cannon") {
  63469. physicsPlugin = new BABYLON.CannonJSPlugin();
  63470. }
  63471. else if (parsedData.physicsEngine === "oimo") {
  63472. physicsPlugin = new BABYLON.OimoJSPlugin();
  63473. }
  63474. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  63475. //else - default engine, which is currently oimo
  63476. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  63477. scene.enablePhysics(physicsGravity, physicsPlugin);
  63478. }
  63479. // Metadata
  63480. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  63481. scene.metadata = parsedData.metadata;
  63482. }
  63483. //collisions, if defined. otherwise, default is true
  63484. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  63485. scene.collisionsEnabled = parsedData.collisionsEnabled;
  63486. }
  63487. scene.workerCollisions = !!parsedData.workerCollisions;
  63488. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  63489. if (!container) {
  63490. return false;
  63491. }
  63492. if (parsedData.autoAnimate) {
  63493. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  63494. }
  63495. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  63496. scene.setActiveCameraByID(parsedData.activeCameraID);
  63497. }
  63498. // Environment texture
  63499. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  63500. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  63501. if (parsedData.createDefaultSkybox === true) {
  63502. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  63503. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  63504. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  63505. }
  63506. }
  63507. // Finish
  63508. return true;
  63509. }
  63510. catch (err) {
  63511. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  63512. if (onError) {
  63513. onError(msg, err);
  63514. }
  63515. else {
  63516. BABYLON.Tools.Log(msg);
  63517. throw err;
  63518. }
  63519. }
  63520. finally {
  63521. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63522. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63523. }
  63524. }
  63525. return false;
  63526. },
  63527. loadAssetContainer: function (scene, data, rootUrl, onError) {
  63528. var container = loadAssetContainer(scene, data, rootUrl, onError);
  63529. return container;
  63530. }
  63531. });
  63532. })(BABYLON || (BABYLON = {}));
  63533. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  63534. "use strict";
  63535. var BABYLON;
  63536. (function (BABYLON) {
  63537. var FilesInput = /** @class */ (function () {
  63538. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  63539. this.onProcessFileCallback = function () { return true; };
  63540. this._engine = engine;
  63541. this._currentScene = scene;
  63542. this._sceneLoadedCallback = sceneLoadedCallback;
  63543. this._progressCallback = progressCallback;
  63544. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  63545. this._textureLoadingCallback = textureLoadingCallback;
  63546. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  63547. this._onReloadCallback = onReloadCallback;
  63548. this._errorCallback = errorCallback;
  63549. }
  63550. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  63551. var _this = this;
  63552. if (elementToMonitor) {
  63553. this._elementToMonitor = elementToMonitor;
  63554. this._dragEnterHandler = function (e) { _this.drag(e); };
  63555. this._dragOverHandler = function (e) { _this.drag(e); };
  63556. this._dropHandler = function (e) { _this.drop(e); };
  63557. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  63558. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  63559. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  63560. }
  63561. };
  63562. FilesInput.prototype.dispose = function () {
  63563. if (!this._elementToMonitor) {
  63564. return;
  63565. }
  63566. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  63567. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  63568. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  63569. };
  63570. FilesInput.prototype.renderFunction = function () {
  63571. if (this._additionalRenderLoopLogicCallback) {
  63572. this._additionalRenderLoopLogicCallback();
  63573. }
  63574. if (this._currentScene) {
  63575. if (this._textureLoadingCallback) {
  63576. var remaining = this._currentScene.getWaitingItemsCount();
  63577. if (remaining > 0) {
  63578. this._textureLoadingCallback(remaining);
  63579. }
  63580. }
  63581. this._currentScene.render();
  63582. }
  63583. };
  63584. FilesInput.prototype.drag = function (e) {
  63585. e.stopPropagation();
  63586. e.preventDefault();
  63587. };
  63588. FilesInput.prototype.drop = function (eventDrop) {
  63589. eventDrop.stopPropagation();
  63590. eventDrop.preventDefault();
  63591. this.loadFiles(eventDrop);
  63592. };
  63593. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  63594. var _this = this;
  63595. var reader = folder.createReader();
  63596. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  63597. reader.readEntries(function (entries) {
  63598. remaining.count += entries.length;
  63599. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  63600. var entry = entries_1[_i];
  63601. if (entry.isFile) {
  63602. entry.file(function (file) {
  63603. file.correctName = relativePath + file.name;
  63604. files.push(file);
  63605. if (--remaining.count === 0) {
  63606. callback();
  63607. }
  63608. });
  63609. }
  63610. else if (entry.isDirectory) {
  63611. _this._traverseFolder(entry, files, remaining, callback);
  63612. }
  63613. }
  63614. if (--remaining.count) {
  63615. callback();
  63616. }
  63617. });
  63618. };
  63619. FilesInput.prototype._processFiles = function (files) {
  63620. for (var i = 0; i < files.length; i++) {
  63621. var name = files[i].correctName.toLowerCase();
  63622. var extension = name.split('.').pop();
  63623. if (!this.onProcessFileCallback(files[i], name, extension)) {
  63624. continue;
  63625. }
  63626. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  63627. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  63628. this._sceneFileToLoad = files[i];
  63629. }
  63630. else {
  63631. FilesInput.FilesToLoad[name] = files[i];
  63632. }
  63633. }
  63634. };
  63635. FilesInput.prototype.loadFiles = function (event) {
  63636. var _this = this;
  63637. if (this._startingProcessingFilesCallback)
  63638. this._startingProcessingFilesCallback();
  63639. // Handling data transfer via drag'n'drop
  63640. if (event && event.dataTransfer && event.dataTransfer.files) {
  63641. this._filesToLoad = event.dataTransfer.files;
  63642. }
  63643. // Handling files from input files
  63644. if (event && event.target && event.target.files) {
  63645. this._filesToLoad = event.target.files;
  63646. }
  63647. if (this._filesToLoad && this._filesToLoad.length > 0) {
  63648. var files_1 = new Array();
  63649. var folders = [];
  63650. var items = event.dataTransfer ? event.dataTransfer.items : null;
  63651. for (var i = 0; i < this._filesToLoad.length; i++) {
  63652. var fileToLoad = this._filesToLoad[i];
  63653. var name_1 = fileToLoad.name.toLowerCase();
  63654. var entry = void 0;
  63655. fileToLoad.correctName = name_1;
  63656. if (items) {
  63657. var item = items[i];
  63658. if (item.getAsEntry) {
  63659. entry = item.getAsEntry();
  63660. }
  63661. else if (item.webkitGetAsEntry) {
  63662. entry = item.webkitGetAsEntry();
  63663. }
  63664. }
  63665. if (!entry) {
  63666. files_1.push(fileToLoad);
  63667. }
  63668. else {
  63669. if (entry.isDirectory) {
  63670. folders.push(entry);
  63671. }
  63672. else {
  63673. files_1.push(fileToLoad);
  63674. }
  63675. }
  63676. }
  63677. if (folders.length === 0) {
  63678. this._processFiles(files_1);
  63679. this._processReload();
  63680. }
  63681. else {
  63682. var remaining = { count: folders.length };
  63683. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  63684. var folder = folders_1[_i];
  63685. this._traverseFolder(folder, files_1, remaining, function () {
  63686. _this._processFiles(files_1);
  63687. if (remaining.count === 0) {
  63688. _this._processReload();
  63689. }
  63690. });
  63691. }
  63692. }
  63693. }
  63694. };
  63695. FilesInput.prototype._processReload = function () {
  63696. if (this._onReloadCallback) {
  63697. this._onReloadCallback(this._sceneFileToLoad);
  63698. }
  63699. else {
  63700. this.reload();
  63701. }
  63702. };
  63703. FilesInput.prototype.reload = function () {
  63704. var _this = this;
  63705. // If a scene file has been provided
  63706. if (this._sceneFileToLoad) {
  63707. if (this._currentScene) {
  63708. if (BABYLON.Tools.errorsCount > 0) {
  63709. BABYLON.Tools.ClearLogCache();
  63710. }
  63711. this._engine.stopRenderLoop();
  63712. this._currentScene.dispose();
  63713. }
  63714. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  63715. if (_this._progressCallback) {
  63716. _this._progressCallback(progress);
  63717. }
  63718. }).then(function (scene) {
  63719. _this._currentScene = scene;
  63720. if (_this._sceneLoadedCallback) {
  63721. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  63722. }
  63723. // Wait for textures and shaders to be ready
  63724. _this._currentScene.executeWhenReady(function () {
  63725. _this._engine.runRenderLoop(function () {
  63726. _this.renderFunction();
  63727. });
  63728. });
  63729. }).catch(function (error) {
  63730. if (_this._errorCallback) {
  63731. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  63732. }
  63733. });
  63734. }
  63735. else {
  63736. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  63737. }
  63738. };
  63739. FilesInput.FilesToLoad = {};
  63740. return FilesInput;
  63741. }());
  63742. BABYLON.FilesInput = FilesInput;
  63743. })(BABYLON || (BABYLON = {}));
  63744. //# sourceMappingURL=babylon.filesInput.js.map
  63745. "use strict";
  63746. var BABYLON;
  63747. (function (BABYLON) {
  63748. /**
  63749. * This class implement a typical dictionary using a string as key and the generic type T as value.
  63750. * The underlying implementation relies on an associative array to ensure the best performances.
  63751. * The value can be anything including 'null' but except 'undefined'
  63752. */
  63753. var StringDictionary = /** @class */ (function () {
  63754. function StringDictionary() {
  63755. this._count = 0;
  63756. this._data = {};
  63757. }
  63758. /**
  63759. * This will clear this dictionary and copy the content from the 'source' one.
  63760. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  63761. * @param source the dictionary to take the content from and copy to this dictionary
  63762. */
  63763. StringDictionary.prototype.copyFrom = function (source) {
  63764. var _this = this;
  63765. this.clear();
  63766. source.forEach(function (t, v) { return _this.add(t, v); });
  63767. };
  63768. /**
  63769. * Get a value based from its key
  63770. * @param key the given key to get the matching value from
  63771. * @return the value if found, otherwise undefined is returned
  63772. */
  63773. StringDictionary.prototype.get = function (key) {
  63774. var val = this._data[key];
  63775. if (val !== undefined) {
  63776. return val;
  63777. }
  63778. return undefined;
  63779. };
  63780. /**
  63781. * Get a value from its key or add it if it doesn't exist.
  63782. * This method will ensure you that a given key/data will be present in the dictionary.
  63783. * @param key the given key to get the matching value from
  63784. * @param factory the factory that will create the value if the key is not present in the dictionary.
  63785. * The factory will only be invoked if there's no data for the given key.
  63786. * @return the value corresponding to the key.
  63787. */
  63788. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  63789. var val = this.get(key);
  63790. if (val !== undefined) {
  63791. return val;
  63792. }
  63793. val = factory(key);
  63794. if (val) {
  63795. this.add(key, val);
  63796. }
  63797. return val;
  63798. };
  63799. /**
  63800. * Get a value from its key if present in the dictionary otherwise add it
  63801. * @param key the key to get the value from
  63802. * @param val if there's no such key/value pair in the dictionary add it with this value
  63803. * @return the value corresponding to the key
  63804. */
  63805. StringDictionary.prototype.getOrAdd = function (key, val) {
  63806. var curVal = this.get(key);
  63807. if (curVal !== undefined) {
  63808. return curVal;
  63809. }
  63810. this.add(key, val);
  63811. return val;
  63812. };
  63813. /**
  63814. * Check if there's a given key in the dictionary
  63815. * @param key the key to check for
  63816. * @return true if the key is present, false otherwise
  63817. */
  63818. StringDictionary.prototype.contains = function (key) {
  63819. return this._data[key] !== undefined;
  63820. };
  63821. /**
  63822. * Add a new key and its corresponding value
  63823. * @param key the key to add
  63824. * @param value the value corresponding to the key
  63825. * @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
  63826. */
  63827. StringDictionary.prototype.add = function (key, value) {
  63828. if (this._data[key] !== undefined) {
  63829. return false;
  63830. }
  63831. this._data[key] = value;
  63832. ++this._count;
  63833. return true;
  63834. };
  63835. StringDictionary.prototype.set = function (key, value) {
  63836. if (this._data[key] === undefined) {
  63837. return false;
  63838. }
  63839. this._data[key] = value;
  63840. return true;
  63841. };
  63842. /**
  63843. * Get the element of the given key and remove it from the dictionary
  63844. * @param key
  63845. */
  63846. StringDictionary.prototype.getAndRemove = function (key) {
  63847. var val = this.get(key);
  63848. if (val !== undefined) {
  63849. delete this._data[key];
  63850. --this._count;
  63851. return val;
  63852. }
  63853. return null;
  63854. };
  63855. /**
  63856. * Remove a key/value from the dictionary.
  63857. * @param key the key to remove
  63858. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  63859. */
  63860. StringDictionary.prototype.remove = function (key) {
  63861. if (this.contains(key)) {
  63862. delete this._data[key];
  63863. --this._count;
  63864. return true;
  63865. }
  63866. return false;
  63867. };
  63868. /**
  63869. * Clear the whole content of the dictionary
  63870. */
  63871. StringDictionary.prototype.clear = function () {
  63872. this._data = {};
  63873. this._count = 0;
  63874. };
  63875. Object.defineProperty(StringDictionary.prototype, "count", {
  63876. get: function () {
  63877. return this._count;
  63878. },
  63879. enumerable: true,
  63880. configurable: true
  63881. });
  63882. /**
  63883. * Execute a callback on each key/val of the dictionary.
  63884. * Note that you can remove any element in this dictionary in the callback implementation
  63885. * @param callback the callback to execute on a given key/value pair
  63886. */
  63887. StringDictionary.prototype.forEach = function (callback) {
  63888. for (var cur in this._data) {
  63889. var val = this._data[cur];
  63890. callback(cur, val);
  63891. }
  63892. };
  63893. /**
  63894. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  63895. * If the callback returns null or undefined the method will iterate to the next key/value pair
  63896. * Note that you can remove any element in this dictionary in the callback implementation
  63897. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  63898. */
  63899. StringDictionary.prototype.first = function (callback) {
  63900. for (var cur in this._data) {
  63901. var val = this._data[cur];
  63902. var res = callback(cur, val);
  63903. if (res) {
  63904. return res;
  63905. }
  63906. }
  63907. return null;
  63908. };
  63909. return StringDictionary;
  63910. }());
  63911. BABYLON.StringDictionary = StringDictionary;
  63912. })(BABYLON || (BABYLON = {}));
  63913. //# sourceMappingURL=babylon.stringDictionary.js.map
  63914. "use strict";
  63915. var BABYLON;
  63916. (function (BABYLON) {
  63917. var Tags = /** @class */ (function () {
  63918. function Tags() {
  63919. }
  63920. Tags.EnableFor = function (obj) {
  63921. obj._tags = obj._tags || {};
  63922. obj.hasTags = function () {
  63923. return Tags.HasTags(obj);
  63924. };
  63925. obj.addTags = function (tagsString) {
  63926. return Tags.AddTagsTo(obj, tagsString);
  63927. };
  63928. obj.removeTags = function (tagsString) {
  63929. return Tags.RemoveTagsFrom(obj, tagsString);
  63930. };
  63931. obj.matchesTagsQuery = function (tagsQuery) {
  63932. return Tags.MatchesQuery(obj, tagsQuery);
  63933. };
  63934. };
  63935. Tags.DisableFor = function (obj) {
  63936. delete obj._tags;
  63937. delete obj.hasTags;
  63938. delete obj.addTags;
  63939. delete obj.removeTags;
  63940. delete obj.matchesTagsQuery;
  63941. };
  63942. Tags.HasTags = function (obj) {
  63943. if (!obj._tags) {
  63944. return false;
  63945. }
  63946. return !BABYLON.Tools.IsEmpty(obj._tags);
  63947. };
  63948. Tags.GetTags = function (obj, asString) {
  63949. if (asString === void 0) { asString = true; }
  63950. if (!obj._tags) {
  63951. return null;
  63952. }
  63953. if (asString) {
  63954. var tagsArray = [];
  63955. for (var tag in obj._tags) {
  63956. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  63957. tagsArray.push(tag);
  63958. }
  63959. }
  63960. return tagsArray.join(" ");
  63961. }
  63962. else {
  63963. return obj._tags;
  63964. }
  63965. };
  63966. // the tags 'true' and 'false' are reserved and cannot be used as tags
  63967. // a tag cannot start with '||', '&&', and '!'
  63968. // it cannot contain whitespaces
  63969. Tags.AddTagsTo = function (obj, tagsString) {
  63970. if (!tagsString) {
  63971. return;
  63972. }
  63973. if (typeof tagsString !== "string") {
  63974. return;
  63975. }
  63976. var tags = tagsString.split(" ");
  63977. tags.forEach(function (tag, index, array) {
  63978. Tags._AddTagTo(obj, tag);
  63979. });
  63980. };
  63981. Tags._AddTagTo = function (obj, tag) {
  63982. tag = tag.trim();
  63983. if (tag === "" || tag === "true" || tag === "false") {
  63984. return;
  63985. }
  63986. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  63987. return;
  63988. }
  63989. Tags.EnableFor(obj);
  63990. obj._tags[tag] = true;
  63991. };
  63992. Tags.RemoveTagsFrom = function (obj, tagsString) {
  63993. if (!Tags.HasTags(obj)) {
  63994. return;
  63995. }
  63996. var tags = tagsString.split(" ");
  63997. for (var t in tags) {
  63998. Tags._RemoveTagFrom(obj, tags[t]);
  63999. }
  64000. };
  64001. Tags._RemoveTagFrom = function (obj, tag) {
  64002. delete obj._tags[tag];
  64003. };
  64004. Tags.MatchesQuery = function (obj, tagsQuery) {
  64005. if (tagsQuery === undefined) {
  64006. return true;
  64007. }
  64008. if (tagsQuery === "") {
  64009. return Tags.HasTags(obj);
  64010. }
  64011. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  64012. };
  64013. return Tags;
  64014. }());
  64015. BABYLON.Tags = Tags;
  64016. })(BABYLON || (BABYLON = {}));
  64017. //# sourceMappingURL=babylon.tags.js.map
  64018. "use strict";
  64019. var BABYLON;
  64020. (function (BABYLON) {
  64021. var AndOrNotEvaluator = /** @class */ (function () {
  64022. function AndOrNotEvaluator() {
  64023. }
  64024. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  64025. if (!query.match(/\([^\(\)]*\)/g)) {
  64026. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  64027. }
  64028. else {
  64029. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  64030. // remove parenthesis
  64031. r = r.slice(1, r.length - 1);
  64032. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  64033. });
  64034. }
  64035. if (query === "true") {
  64036. return true;
  64037. }
  64038. if (query === "false") {
  64039. return false;
  64040. }
  64041. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  64042. };
  64043. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  64044. evaluateCallback = evaluateCallback || (function (r) {
  64045. return r === "true" ? true : false;
  64046. });
  64047. var result;
  64048. var or = parenthesisContent.split("||");
  64049. for (var i in or) {
  64050. if (or.hasOwnProperty(i)) {
  64051. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  64052. var and = ori.split("&&");
  64053. if (and.length > 1) {
  64054. for (var j = 0; j < and.length; ++j) {
  64055. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  64056. if (andj !== "true" && andj !== "false") {
  64057. if (andj[0] === "!") {
  64058. result = !evaluateCallback(andj.substring(1));
  64059. }
  64060. else {
  64061. result = evaluateCallback(andj);
  64062. }
  64063. }
  64064. else {
  64065. result = andj === "true" ? true : false;
  64066. }
  64067. if (!result) {
  64068. ori = "false";
  64069. break;
  64070. }
  64071. }
  64072. }
  64073. if (result || ori === "true") {
  64074. result = true;
  64075. break;
  64076. }
  64077. // result equals false (or undefined)
  64078. if (ori !== "true" && ori !== "false") {
  64079. if (ori[0] === "!") {
  64080. result = !evaluateCallback(ori.substring(1));
  64081. }
  64082. else {
  64083. result = evaluateCallback(ori);
  64084. }
  64085. }
  64086. else {
  64087. result = ori === "true" ? true : false;
  64088. }
  64089. }
  64090. }
  64091. // the whole parenthesis scope is replaced by 'true' or 'false'
  64092. return result ? "true" : "false";
  64093. };
  64094. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  64095. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  64096. // remove whitespaces
  64097. r = r.replace(/[\s]/g, function () { return ""; });
  64098. return r.length % 2 ? "!" : "";
  64099. });
  64100. booleanString = booleanString.trim();
  64101. if (booleanString === "!true") {
  64102. booleanString = "false";
  64103. }
  64104. else if (booleanString === "!false") {
  64105. booleanString = "true";
  64106. }
  64107. return booleanString;
  64108. };
  64109. return AndOrNotEvaluator;
  64110. }());
  64111. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  64112. })(BABYLON || (BABYLON = {}));
  64113. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  64114. "use strict";
  64115. var BABYLON;
  64116. (function (BABYLON) {
  64117. var Database = /** @class */ (function () {
  64118. function Database(urlToScene, callbackManifestChecked) {
  64119. // Handling various flavors of prefixed version of IndexedDB
  64120. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  64121. this.callbackManifestChecked = callbackManifestChecked;
  64122. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  64123. this.db = null;
  64124. this._enableSceneOffline = false;
  64125. this._enableTexturesOffline = false;
  64126. this.manifestVersionFound = 0;
  64127. this.mustUpdateRessources = false;
  64128. this.hasReachedQuota = false;
  64129. if (!Database.IDBStorageEnabled) {
  64130. this.callbackManifestChecked(true);
  64131. }
  64132. else {
  64133. this.checkManifestFile();
  64134. }
  64135. }
  64136. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  64137. get: function () {
  64138. return this._enableSceneOffline;
  64139. },
  64140. enumerable: true,
  64141. configurable: true
  64142. });
  64143. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  64144. get: function () {
  64145. return this._enableTexturesOffline;
  64146. },
  64147. enumerable: true,
  64148. configurable: true
  64149. });
  64150. Database.prototype.checkManifestFile = function () {
  64151. var _this = this;
  64152. var noManifestFile = function () {
  64153. _this._enableSceneOffline = false;
  64154. _this._enableTexturesOffline = false;
  64155. _this.callbackManifestChecked(false);
  64156. };
  64157. var timeStampUsed = false;
  64158. var manifestURL = this.currentSceneUrl + ".manifest";
  64159. var xhr = new XMLHttpRequest();
  64160. if (navigator.onLine) {
  64161. // Adding a timestamp to by-pass browsers' cache
  64162. timeStampUsed = true;
  64163. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  64164. }
  64165. xhr.open("GET", manifestURL, true);
  64166. xhr.addEventListener("load", function () {
  64167. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64168. try {
  64169. var manifestFile = JSON.parse(xhr.response);
  64170. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  64171. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  64172. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  64173. _this.manifestVersionFound = manifestFile.version;
  64174. }
  64175. if (_this.callbackManifestChecked) {
  64176. _this.callbackManifestChecked(true);
  64177. }
  64178. }
  64179. catch (ex) {
  64180. noManifestFile();
  64181. }
  64182. }
  64183. else {
  64184. noManifestFile();
  64185. }
  64186. }, false);
  64187. xhr.addEventListener("error", function (event) {
  64188. if (timeStampUsed) {
  64189. timeStampUsed = false;
  64190. // Let's retry without the timeStamp
  64191. // It could fail when coupled with HTML5 Offline API
  64192. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  64193. xhr.open("GET", retryManifestURL, true);
  64194. xhr.send();
  64195. }
  64196. else {
  64197. noManifestFile();
  64198. }
  64199. }, false);
  64200. try {
  64201. xhr.send();
  64202. }
  64203. catch (ex) {
  64204. BABYLON.Tools.Error("Error on XHR send request.");
  64205. this.callbackManifestChecked(false);
  64206. }
  64207. };
  64208. Database.prototype.openAsync = function (successCallback, errorCallback) {
  64209. var _this = this;
  64210. var handleError = function () {
  64211. _this.isSupported = false;
  64212. if (errorCallback)
  64213. errorCallback();
  64214. };
  64215. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  64216. // Your browser doesn't support IndexedDB
  64217. this.isSupported = false;
  64218. if (errorCallback)
  64219. errorCallback();
  64220. }
  64221. else {
  64222. // If the DB hasn't been opened or created yet
  64223. if (!this.db) {
  64224. this.hasReachedQuota = false;
  64225. this.isSupported = true;
  64226. var request = this.idbFactory.open("babylonjs", 1);
  64227. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  64228. request.onerror = function (event) {
  64229. handleError();
  64230. };
  64231. // executes when a version change transaction cannot complete due to other active transactions
  64232. request.onblocked = function (event) {
  64233. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  64234. handleError();
  64235. };
  64236. // DB has been opened successfully
  64237. request.onsuccess = function (event) {
  64238. _this.db = request.result;
  64239. successCallback();
  64240. };
  64241. // Initialization of the DB. Creating Scenes & Textures stores
  64242. request.onupgradeneeded = function (event) {
  64243. _this.db = (event.target).result;
  64244. if (_this.db) {
  64245. try {
  64246. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  64247. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  64248. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  64249. }
  64250. catch (ex) {
  64251. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  64252. handleError();
  64253. }
  64254. }
  64255. };
  64256. }
  64257. else {
  64258. if (successCallback)
  64259. successCallback();
  64260. }
  64261. }
  64262. };
  64263. Database.prototype.loadImageFromDB = function (url, image) {
  64264. var _this = this;
  64265. var completeURL = Database.ReturnFullUrlLocation(url);
  64266. var saveAndLoadImage = function () {
  64267. if (!_this.hasReachedQuota && _this.db !== null) {
  64268. // the texture is not yet in the DB, let's try to save it
  64269. _this._saveImageIntoDBAsync(completeURL, image);
  64270. }
  64271. else {
  64272. image.src = url;
  64273. }
  64274. };
  64275. if (!this.mustUpdateRessources) {
  64276. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  64277. }
  64278. else {
  64279. saveAndLoadImage();
  64280. }
  64281. };
  64282. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  64283. if (this.isSupported && this.db !== null) {
  64284. var texture;
  64285. var transaction = this.db.transaction(["textures"]);
  64286. transaction.onabort = function (event) {
  64287. image.src = url;
  64288. };
  64289. transaction.oncomplete = function (event) {
  64290. var blobTextureURL;
  64291. if (texture) {
  64292. var URL = window.URL || window.webkitURL;
  64293. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  64294. image.onerror = function () {
  64295. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  64296. image.src = url;
  64297. };
  64298. image.src = blobTextureURL;
  64299. }
  64300. else {
  64301. notInDBCallback();
  64302. }
  64303. };
  64304. var getRequest = transaction.objectStore("textures").get(url);
  64305. getRequest.onsuccess = function (event) {
  64306. texture = (event.target).result;
  64307. };
  64308. getRequest.onerror = function (event) {
  64309. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  64310. image.src = url;
  64311. };
  64312. }
  64313. else {
  64314. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64315. image.src = url;
  64316. }
  64317. };
  64318. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  64319. var _this = this;
  64320. if (this.isSupported) {
  64321. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  64322. var generateBlobUrl = function () {
  64323. var blobTextureURL;
  64324. if (blob) {
  64325. var URL = window.URL || window.webkitURL;
  64326. try {
  64327. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  64328. }
  64329. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  64330. catch (ex) {
  64331. blobTextureURL = URL.createObjectURL(blob);
  64332. }
  64333. }
  64334. if (blobTextureURL) {
  64335. image.src = blobTextureURL;
  64336. }
  64337. };
  64338. if (Database.IsUASupportingBlobStorage) {
  64339. var xhr = new XMLHttpRequest(), blob;
  64340. xhr.open("GET", url, true);
  64341. xhr.responseType = "blob";
  64342. xhr.addEventListener("load", function () {
  64343. if (xhr.status === 200 && _this.db) {
  64344. // Blob as response (XHR2)
  64345. blob = xhr.response;
  64346. var transaction = _this.db.transaction(["textures"], "readwrite");
  64347. // the transaction could abort because of a QuotaExceededError error
  64348. transaction.onabort = function (event) {
  64349. try {
  64350. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64351. var srcElement = (event.srcElement || event.target);
  64352. var error = srcElement.error;
  64353. if (error && error.name === "QuotaExceededError") {
  64354. _this.hasReachedQuota = true;
  64355. }
  64356. }
  64357. catch (ex) { }
  64358. generateBlobUrl();
  64359. };
  64360. transaction.oncomplete = function (event) {
  64361. generateBlobUrl();
  64362. };
  64363. var newTexture = { textureUrl: url, data: blob };
  64364. try {
  64365. // Put the blob into the dabase
  64366. var addRequest = transaction.objectStore("textures").put(newTexture);
  64367. addRequest.onsuccess = function (event) {
  64368. };
  64369. addRequest.onerror = function (event) {
  64370. generateBlobUrl();
  64371. };
  64372. }
  64373. catch (ex) {
  64374. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  64375. if (ex.code === 25) {
  64376. Database.IsUASupportingBlobStorage = false;
  64377. }
  64378. image.src = url;
  64379. }
  64380. }
  64381. else {
  64382. image.src = url;
  64383. }
  64384. }, false);
  64385. xhr.addEventListener("error", function (event) {
  64386. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  64387. image.src = url;
  64388. }, false);
  64389. xhr.send();
  64390. }
  64391. else {
  64392. image.src = url;
  64393. }
  64394. }
  64395. else {
  64396. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64397. image.src = url;
  64398. }
  64399. };
  64400. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  64401. var _this = this;
  64402. var updateVersion = function () {
  64403. // the version is not yet in the DB or we need to update it
  64404. _this._saveVersionIntoDBAsync(url, versionLoaded);
  64405. };
  64406. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  64407. };
  64408. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  64409. var _this = this;
  64410. if (this.isSupported && this.db) {
  64411. var version;
  64412. try {
  64413. var transaction = this.db.transaction(["versions"]);
  64414. transaction.oncomplete = function (event) {
  64415. if (version) {
  64416. // If the version in the JSON file is > than the version in DB
  64417. if (_this.manifestVersionFound > version.data) {
  64418. _this.mustUpdateRessources = true;
  64419. updateInDBCallback();
  64420. }
  64421. else {
  64422. callback(version.data);
  64423. }
  64424. }
  64425. else {
  64426. _this.mustUpdateRessources = true;
  64427. updateInDBCallback();
  64428. }
  64429. };
  64430. transaction.onabort = function (event) {
  64431. callback(-1);
  64432. };
  64433. var getRequest = transaction.objectStore("versions").get(url);
  64434. getRequest.onsuccess = function (event) {
  64435. version = (event.target).result;
  64436. };
  64437. getRequest.onerror = function (event) {
  64438. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  64439. callback(-1);
  64440. };
  64441. }
  64442. catch (ex) {
  64443. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  64444. callback(-1);
  64445. }
  64446. }
  64447. else {
  64448. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64449. callback(-1);
  64450. }
  64451. };
  64452. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  64453. var _this = this;
  64454. if (this.isSupported && !this.hasReachedQuota && this.db) {
  64455. try {
  64456. // Open a transaction to the database
  64457. var transaction = this.db.transaction(["versions"], "readwrite");
  64458. // the transaction could abort because of a QuotaExceededError error
  64459. transaction.onabort = function (event) {
  64460. try {
  64461. var error = event.srcElement['error'];
  64462. if (error && error.name === "QuotaExceededError") {
  64463. _this.hasReachedQuota = true;
  64464. }
  64465. }
  64466. catch (ex) { }
  64467. callback(-1);
  64468. };
  64469. transaction.oncomplete = function (event) {
  64470. callback(_this.manifestVersionFound);
  64471. };
  64472. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  64473. // Put the scene into the database
  64474. var addRequest = transaction.objectStore("versions").put(newVersion);
  64475. addRequest.onsuccess = function (event) {
  64476. };
  64477. addRequest.onerror = function (event) {
  64478. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  64479. };
  64480. }
  64481. catch (ex) {
  64482. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  64483. callback(-1);
  64484. }
  64485. }
  64486. else {
  64487. callback(-1);
  64488. }
  64489. };
  64490. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  64491. var _this = this;
  64492. var completeUrl = Database.ReturnFullUrlLocation(url);
  64493. var saveAndLoadFile = function () {
  64494. // the scene is not yet in the DB, let's try to save it
  64495. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  64496. };
  64497. this._checkVersionFromDB(completeUrl, function (version) {
  64498. if (version !== -1) {
  64499. if (!_this.mustUpdateRessources) {
  64500. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  64501. }
  64502. else {
  64503. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  64504. }
  64505. }
  64506. else {
  64507. if (errorCallback) {
  64508. errorCallback();
  64509. }
  64510. }
  64511. });
  64512. };
  64513. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  64514. if (this.isSupported && this.db) {
  64515. var targetStore;
  64516. if (url.indexOf(".babylon") !== -1) {
  64517. targetStore = "scenes";
  64518. }
  64519. else {
  64520. targetStore = "textures";
  64521. }
  64522. var file;
  64523. var transaction = this.db.transaction([targetStore]);
  64524. transaction.oncomplete = function (event) {
  64525. if (file) {
  64526. callback(file.data);
  64527. }
  64528. else {
  64529. notInDBCallback();
  64530. }
  64531. };
  64532. transaction.onabort = function (event) {
  64533. notInDBCallback();
  64534. };
  64535. var getRequest = transaction.objectStore(targetStore).get(url);
  64536. getRequest.onsuccess = function (event) {
  64537. file = (event.target).result;
  64538. };
  64539. getRequest.onerror = function (event) {
  64540. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  64541. notInDBCallback();
  64542. };
  64543. }
  64544. else {
  64545. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64546. callback();
  64547. }
  64548. };
  64549. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  64550. var _this = this;
  64551. if (this.isSupported) {
  64552. var targetStore;
  64553. if (url.indexOf(".babylon") !== -1) {
  64554. targetStore = "scenes";
  64555. }
  64556. else {
  64557. targetStore = "textures";
  64558. }
  64559. // Create XHR
  64560. var xhr = new XMLHttpRequest();
  64561. var fileData;
  64562. xhr.open("GET", url, true);
  64563. if (useArrayBuffer) {
  64564. xhr.responseType = "arraybuffer";
  64565. }
  64566. if (progressCallback) {
  64567. xhr.onprogress = progressCallback;
  64568. }
  64569. xhr.addEventListener("load", function () {
  64570. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  64571. // Blob as response (XHR2)
  64572. //fileData = xhr.responseText;
  64573. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  64574. if (!_this.hasReachedQuota && _this.db) {
  64575. // Open a transaction to the database
  64576. var transaction = _this.db.transaction([targetStore], "readwrite");
  64577. // the transaction could abort because of a QuotaExceededError error
  64578. transaction.onabort = function (event) {
  64579. try {
  64580. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64581. var error = event.srcElement['error'];
  64582. if (error && error.name === "QuotaExceededError") {
  64583. _this.hasReachedQuota = true;
  64584. }
  64585. }
  64586. catch (ex) { }
  64587. callback(fileData);
  64588. };
  64589. transaction.oncomplete = function (event) {
  64590. callback(fileData);
  64591. };
  64592. var newFile;
  64593. if (targetStore === "scenes") {
  64594. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  64595. }
  64596. else {
  64597. newFile = { textureUrl: url, data: fileData };
  64598. }
  64599. try {
  64600. // Put the scene into the database
  64601. var addRequest = transaction.objectStore(targetStore).put(newFile);
  64602. addRequest.onsuccess = function (event) {
  64603. };
  64604. addRequest.onerror = function (event) {
  64605. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  64606. };
  64607. }
  64608. catch (ex) {
  64609. callback(fileData);
  64610. }
  64611. }
  64612. else {
  64613. callback(fileData);
  64614. }
  64615. }
  64616. else {
  64617. callback();
  64618. }
  64619. }, false);
  64620. xhr.addEventListener("error", function (event) {
  64621. BABYLON.Tools.Error("error on XHR request.");
  64622. callback();
  64623. }, false);
  64624. xhr.send();
  64625. }
  64626. else {
  64627. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64628. callback();
  64629. }
  64630. };
  64631. Database.IsUASupportingBlobStorage = true;
  64632. Database.IDBStorageEnabled = true;
  64633. Database.parseURL = function (url) {
  64634. var a = document.createElement('a');
  64635. a.href = url;
  64636. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  64637. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  64638. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  64639. return absLocation;
  64640. };
  64641. Database.ReturnFullUrlLocation = function (url) {
  64642. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  64643. return (Database.parseURL(window.location.href) + url);
  64644. }
  64645. else {
  64646. return url;
  64647. }
  64648. };
  64649. return Database;
  64650. }());
  64651. BABYLON.Database = Database;
  64652. })(BABYLON || (BABYLON = {}));
  64653. //# sourceMappingURL=babylon.database.js.map
  64654. "use strict";
  64655. var BABYLON;
  64656. (function (BABYLON) {
  64657. var FresnelParameters = /** @class */ (function () {
  64658. function FresnelParameters() {
  64659. this._isEnabled = true;
  64660. this.leftColor = BABYLON.Color3.White();
  64661. this.rightColor = BABYLON.Color3.Black();
  64662. this.bias = 0;
  64663. this.power = 1;
  64664. }
  64665. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  64666. get: function () {
  64667. return this._isEnabled;
  64668. },
  64669. set: function (value) {
  64670. if (this._isEnabled === value) {
  64671. return;
  64672. }
  64673. this._isEnabled = value;
  64674. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  64675. },
  64676. enumerable: true,
  64677. configurable: true
  64678. });
  64679. FresnelParameters.prototype.clone = function () {
  64680. var newFresnelParameters = new FresnelParameters();
  64681. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  64682. return newFresnelParameters;
  64683. };
  64684. FresnelParameters.prototype.serialize = function () {
  64685. var serializationObject = {};
  64686. serializationObject.isEnabled = this.isEnabled;
  64687. serializationObject.leftColor = this.leftColor;
  64688. serializationObject.rightColor = this.rightColor;
  64689. serializationObject.bias = this.bias;
  64690. serializationObject.power = this.power;
  64691. return serializationObject;
  64692. };
  64693. FresnelParameters.Parse = function (parsedFresnelParameters) {
  64694. var fresnelParameters = new FresnelParameters();
  64695. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  64696. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  64697. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  64698. fresnelParameters.bias = parsedFresnelParameters.bias;
  64699. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  64700. return fresnelParameters;
  64701. };
  64702. return FresnelParameters;
  64703. }());
  64704. BABYLON.FresnelParameters = FresnelParameters;
  64705. })(BABYLON || (BABYLON = {}));
  64706. //# sourceMappingURL=babylon.fresnelParameters.js.map
  64707. "use strict";
  64708. var BABYLON;
  64709. (function (BABYLON) {
  64710. var MultiMaterial = /** @class */ (function (_super) {
  64711. __extends(MultiMaterial, _super);
  64712. function MultiMaterial(name, scene) {
  64713. var _this = _super.call(this, name, scene, true) || this;
  64714. scene.multiMaterials.push(_this);
  64715. _this.subMaterials = new Array();
  64716. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  64717. return _this;
  64718. }
  64719. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  64720. get: function () {
  64721. return this._subMaterials;
  64722. },
  64723. set: function (value) {
  64724. this._subMaterials = value;
  64725. this._hookArray(value);
  64726. },
  64727. enumerable: true,
  64728. configurable: true
  64729. });
  64730. MultiMaterial.prototype._hookArray = function (array) {
  64731. var _this = this;
  64732. var oldPush = array.push;
  64733. array.push = function () {
  64734. var items = [];
  64735. for (var _i = 0; _i < arguments.length; _i++) {
  64736. items[_i] = arguments[_i];
  64737. }
  64738. var result = oldPush.apply(array, items);
  64739. _this._markAllSubMeshesAsTexturesDirty();
  64740. return result;
  64741. };
  64742. var oldSplice = array.splice;
  64743. array.splice = function (index, deleteCount) {
  64744. var deleted = oldSplice.apply(array, [index, deleteCount]);
  64745. _this._markAllSubMeshesAsTexturesDirty();
  64746. return deleted;
  64747. };
  64748. };
  64749. // Properties
  64750. MultiMaterial.prototype.getSubMaterial = function (index) {
  64751. if (index < 0 || index >= this.subMaterials.length) {
  64752. return this.getScene().defaultMaterial;
  64753. }
  64754. return this.subMaterials[index];
  64755. };
  64756. MultiMaterial.prototype.getActiveTextures = function () {
  64757. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  64758. if (subMaterial) {
  64759. return subMaterial.getActiveTextures();
  64760. }
  64761. else {
  64762. return [];
  64763. }
  64764. }));
  64765. var _a;
  64766. };
  64767. // Methods
  64768. MultiMaterial.prototype.getClassName = function () {
  64769. return "MultiMaterial";
  64770. };
  64771. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  64772. for (var index = 0; index < this.subMaterials.length; index++) {
  64773. var subMaterial = this.subMaterials[index];
  64774. if (subMaterial) {
  64775. if (subMaterial.storeEffectOnSubMeshes) {
  64776. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  64777. return false;
  64778. }
  64779. continue;
  64780. }
  64781. if (!subMaterial.isReady(mesh)) {
  64782. return false;
  64783. }
  64784. }
  64785. }
  64786. return true;
  64787. };
  64788. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  64789. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  64790. for (var index = 0; index < this.subMaterials.length; index++) {
  64791. var subMaterial = null;
  64792. var current = this.subMaterials[index];
  64793. if (cloneChildren && current) {
  64794. subMaterial = current.clone(name + "-" + current.name);
  64795. }
  64796. else {
  64797. subMaterial = this.subMaterials[index];
  64798. }
  64799. newMultiMaterial.subMaterials.push(subMaterial);
  64800. }
  64801. return newMultiMaterial;
  64802. };
  64803. MultiMaterial.prototype.serialize = function () {
  64804. var serializationObject = {};
  64805. serializationObject.name = this.name;
  64806. serializationObject.id = this.id;
  64807. if (BABYLON.Tags) {
  64808. serializationObject.tags = BABYLON.Tags.GetTags(this);
  64809. }
  64810. serializationObject.materials = [];
  64811. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  64812. var subMat = this.subMaterials[matIndex];
  64813. if (subMat) {
  64814. serializationObject.materials.push(subMat.id);
  64815. }
  64816. else {
  64817. serializationObject.materials.push(null);
  64818. }
  64819. }
  64820. return serializationObject;
  64821. };
  64822. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  64823. var scene = this.getScene();
  64824. if (!scene) {
  64825. return;
  64826. }
  64827. var index = scene.multiMaterials.indexOf(this);
  64828. if (index >= 0) {
  64829. scene.multiMaterials.splice(index, 1);
  64830. }
  64831. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  64832. };
  64833. return MultiMaterial;
  64834. }(BABYLON.Material));
  64835. BABYLON.MultiMaterial = MultiMaterial;
  64836. })(BABYLON || (BABYLON = {}));
  64837. //# sourceMappingURL=babylon.multiMaterial.js.map
  64838. "use strict";
  64839. var BABYLON;
  64840. (function (BABYLON) {
  64841. var FreeCameraTouchInput = /** @class */ (function () {
  64842. function FreeCameraTouchInput() {
  64843. this._offsetX = null;
  64844. this._offsetY = null;
  64845. this._pointerPressed = new Array();
  64846. this.touchAngularSensibility = 200000.0;
  64847. this.touchMoveSensibility = 250.0;
  64848. }
  64849. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  64850. var _this = this;
  64851. var previousPosition = null;
  64852. if (this._pointerInput === undefined) {
  64853. this._onLostFocus = function (evt) {
  64854. _this._offsetX = null;
  64855. _this._offsetY = null;
  64856. };
  64857. this._pointerInput = function (p, s) {
  64858. var evt = p.event;
  64859. if (evt.pointerType === "mouse") {
  64860. return;
  64861. }
  64862. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  64863. if (!noPreventDefault) {
  64864. evt.preventDefault();
  64865. }
  64866. _this._pointerPressed.push(evt.pointerId);
  64867. if (_this._pointerPressed.length !== 1) {
  64868. return;
  64869. }
  64870. previousPosition = {
  64871. x: evt.clientX,
  64872. y: evt.clientY
  64873. };
  64874. }
  64875. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  64876. if (!noPreventDefault) {
  64877. evt.preventDefault();
  64878. }
  64879. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64880. if (index === -1) {
  64881. return;
  64882. }
  64883. _this._pointerPressed.splice(index, 1);
  64884. if (index != 0) {
  64885. return;
  64886. }
  64887. previousPosition = null;
  64888. _this._offsetX = null;
  64889. _this._offsetY = null;
  64890. }
  64891. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  64892. if (!noPreventDefault) {
  64893. evt.preventDefault();
  64894. }
  64895. if (!previousPosition) {
  64896. return;
  64897. }
  64898. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64899. if (index != 0) {
  64900. return;
  64901. }
  64902. _this._offsetX = evt.clientX - previousPosition.x;
  64903. _this._offsetY = -(evt.clientY - previousPosition.y);
  64904. }
  64905. };
  64906. }
  64907. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  64908. if (this._onLostFocus) {
  64909. element.addEventListener("blur", this._onLostFocus);
  64910. }
  64911. };
  64912. FreeCameraTouchInput.prototype.detachControl = function (element) {
  64913. if (this._pointerInput && element) {
  64914. if (this._observer) {
  64915. this.camera.getScene().onPointerObservable.remove(this._observer);
  64916. this._observer = null;
  64917. }
  64918. if (this._onLostFocus) {
  64919. element.removeEventListener("blur", this._onLostFocus);
  64920. this._onLostFocus = null;
  64921. }
  64922. this._pointerPressed = [];
  64923. this._offsetX = null;
  64924. this._offsetY = null;
  64925. }
  64926. };
  64927. FreeCameraTouchInput.prototype.checkInputs = function () {
  64928. if (this._offsetX && this._offsetY) {
  64929. var camera = this.camera;
  64930. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  64931. if (this._pointerPressed.length > 1) {
  64932. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  64933. }
  64934. else {
  64935. var speed = camera._computeLocalCameraSpeed();
  64936. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  64937. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  64938. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  64939. }
  64940. }
  64941. };
  64942. FreeCameraTouchInput.prototype.getClassName = function () {
  64943. return "FreeCameraTouchInput";
  64944. };
  64945. FreeCameraTouchInput.prototype.getSimpleName = function () {
  64946. return "touch";
  64947. };
  64948. __decorate([
  64949. BABYLON.serialize()
  64950. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  64951. __decorate([
  64952. BABYLON.serialize()
  64953. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  64954. return FreeCameraTouchInput;
  64955. }());
  64956. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  64957. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  64958. })(BABYLON || (BABYLON = {}));
  64959. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  64960. "use strict";
  64961. var BABYLON;
  64962. (function (BABYLON) {
  64963. // We're mainly based on the logic defined into the FreeCamera code
  64964. var TouchCamera = /** @class */ (function (_super) {
  64965. __extends(TouchCamera, _super);
  64966. //-- end properties for backward compatibility for inputs
  64967. function TouchCamera(name, position, scene) {
  64968. var _this = _super.call(this, name, position, scene) || this;
  64969. _this.inputs.addTouch();
  64970. _this._setupInputs();
  64971. return _this;
  64972. }
  64973. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  64974. //-- Begin properties for backward compatibility for inputs
  64975. get: function () {
  64976. var touch = this.inputs.attached["touch"];
  64977. if (touch)
  64978. return touch.touchAngularSensibility;
  64979. return 0;
  64980. },
  64981. set: function (value) {
  64982. var touch = this.inputs.attached["touch"];
  64983. if (touch)
  64984. touch.touchAngularSensibility = value;
  64985. },
  64986. enumerable: true,
  64987. configurable: true
  64988. });
  64989. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  64990. get: function () {
  64991. var touch = this.inputs.attached["touch"];
  64992. if (touch)
  64993. return touch.touchMoveSensibility;
  64994. return 0;
  64995. },
  64996. set: function (value) {
  64997. var touch = this.inputs.attached["touch"];
  64998. if (touch)
  64999. touch.touchMoveSensibility = value;
  65000. },
  65001. enumerable: true,
  65002. configurable: true
  65003. });
  65004. TouchCamera.prototype.getClassName = function () {
  65005. return "TouchCamera";
  65006. };
  65007. TouchCamera.prototype._setupInputs = function () {
  65008. var mouse = this.inputs.attached["mouse"];
  65009. if (mouse) {
  65010. mouse.touchEnabled = false;
  65011. }
  65012. };
  65013. return TouchCamera;
  65014. }(BABYLON.FreeCamera));
  65015. BABYLON.TouchCamera = TouchCamera;
  65016. })(BABYLON || (BABYLON = {}));
  65017. //# sourceMappingURL=babylon.touchCamera.js.map
  65018. "use strict";
  65019. var BABYLON;
  65020. (function (BABYLON) {
  65021. var ProceduralTexture = /** @class */ (function (_super) {
  65022. __extends(ProceduralTexture, _super);
  65023. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  65024. if (fallbackTexture === void 0) { fallbackTexture = null; }
  65025. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65026. if (isCube === void 0) { isCube = false; }
  65027. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  65028. _this.isCube = isCube;
  65029. _this.isEnabled = true;
  65030. _this._currentRefreshId = -1;
  65031. _this._refreshRate = 1;
  65032. _this._vertexBuffers = {};
  65033. _this._uniforms = new Array();
  65034. _this._samplers = new Array();
  65035. _this._textures = {};
  65036. _this._floats = {};
  65037. _this._floatsArrays = {};
  65038. _this._colors3 = {};
  65039. _this._colors4 = {};
  65040. _this._vectors2 = {};
  65041. _this._vectors3 = {};
  65042. _this._matrices = {};
  65043. _this._fallbackTextureUsed = false;
  65044. scene._proceduralTextures.push(_this);
  65045. _this._engine = scene.getEngine();
  65046. _this.name = name;
  65047. _this.isRenderTarget = true;
  65048. _this._size = size;
  65049. _this._generateMipMaps = generateMipMaps;
  65050. _this.setFragment(fragment);
  65051. _this._fallbackTexture = fallbackTexture;
  65052. if (isCube) {
  65053. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  65054. _this.setFloat("face", 0);
  65055. }
  65056. else {
  65057. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  65058. }
  65059. // VBO
  65060. var vertices = [];
  65061. vertices.push(1, 1);
  65062. vertices.push(-1, 1);
  65063. vertices.push(-1, -1);
  65064. vertices.push(1, -1);
  65065. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65066. _this._createIndexBuffer();
  65067. return _this;
  65068. }
  65069. ProceduralTexture.prototype._createIndexBuffer = function () {
  65070. var engine = this._engine;
  65071. // Indices
  65072. var indices = [];
  65073. indices.push(0);
  65074. indices.push(1);
  65075. indices.push(2);
  65076. indices.push(0);
  65077. indices.push(2);
  65078. indices.push(3);
  65079. this._indexBuffer = engine.createIndexBuffer(indices);
  65080. };
  65081. ProceduralTexture.prototype._rebuild = function () {
  65082. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65083. if (vb) {
  65084. vb._rebuild();
  65085. }
  65086. this._createIndexBuffer();
  65087. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  65088. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  65089. }
  65090. };
  65091. ProceduralTexture.prototype.reset = function () {
  65092. if (this._effect === undefined) {
  65093. return;
  65094. }
  65095. var engine = this._engine;
  65096. engine._releaseEffect(this._effect);
  65097. };
  65098. ProceduralTexture.prototype.isReady = function () {
  65099. var _this = this;
  65100. var engine = this._engine;
  65101. var shaders;
  65102. if (!this._fragment) {
  65103. return false;
  65104. }
  65105. if (this._fallbackTextureUsed) {
  65106. return true;
  65107. }
  65108. if (this._fragment.fragmentElement !== undefined) {
  65109. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  65110. }
  65111. else {
  65112. shaders = { vertex: "procedural", fragment: this._fragment };
  65113. }
  65114. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  65115. _this.releaseInternalTexture();
  65116. if (_this._fallbackTexture) {
  65117. _this._texture = _this._fallbackTexture._texture;
  65118. if (_this._texture) {
  65119. _this._texture.incrementReferences();
  65120. }
  65121. }
  65122. _this._fallbackTextureUsed = true;
  65123. });
  65124. return this._effect.isReady();
  65125. };
  65126. ProceduralTexture.prototype.resetRefreshCounter = function () {
  65127. this._currentRefreshId = -1;
  65128. };
  65129. ProceduralTexture.prototype.setFragment = function (fragment) {
  65130. this._fragment = fragment;
  65131. };
  65132. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  65133. get: function () {
  65134. return this._refreshRate;
  65135. },
  65136. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  65137. set: function (value) {
  65138. this._refreshRate = value;
  65139. this.resetRefreshCounter();
  65140. },
  65141. enumerable: true,
  65142. configurable: true
  65143. });
  65144. ProceduralTexture.prototype._shouldRender = function () {
  65145. if (!this.isEnabled || !this.isReady() || !this._texture) {
  65146. return false;
  65147. }
  65148. if (this._fallbackTextureUsed) {
  65149. return false;
  65150. }
  65151. if (this._currentRefreshId === -1) {
  65152. this._currentRefreshId = 1;
  65153. return true;
  65154. }
  65155. if (this.refreshRate === this._currentRefreshId) {
  65156. this._currentRefreshId = 1;
  65157. return true;
  65158. }
  65159. this._currentRefreshId++;
  65160. return false;
  65161. };
  65162. ProceduralTexture.prototype.getRenderSize = function () {
  65163. return this._size;
  65164. };
  65165. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  65166. if (this._fallbackTextureUsed) {
  65167. return;
  65168. }
  65169. this.releaseInternalTexture();
  65170. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  65171. };
  65172. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  65173. if (this._uniforms.indexOf(uniformName) === -1) {
  65174. this._uniforms.push(uniformName);
  65175. }
  65176. };
  65177. ProceduralTexture.prototype.setTexture = function (name, texture) {
  65178. if (this._samplers.indexOf(name) === -1) {
  65179. this._samplers.push(name);
  65180. }
  65181. this._textures[name] = texture;
  65182. return this;
  65183. };
  65184. ProceduralTexture.prototype.setFloat = function (name, value) {
  65185. this._checkUniform(name);
  65186. this._floats[name] = value;
  65187. return this;
  65188. };
  65189. ProceduralTexture.prototype.setFloats = function (name, value) {
  65190. this._checkUniform(name);
  65191. this._floatsArrays[name] = value;
  65192. return this;
  65193. };
  65194. ProceduralTexture.prototype.setColor3 = function (name, value) {
  65195. this._checkUniform(name);
  65196. this._colors3[name] = value;
  65197. return this;
  65198. };
  65199. ProceduralTexture.prototype.setColor4 = function (name, value) {
  65200. this._checkUniform(name);
  65201. this._colors4[name] = value;
  65202. return this;
  65203. };
  65204. ProceduralTexture.prototype.setVector2 = function (name, value) {
  65205. this._checkUniform(name);
  65206. this._vectors2[name] = value;
  65207. return this;
  65208. };
  65209. ProceduralTexture.prototype.setVector3 = function (name, value) {
  65210. this._checkUniform(name);
  65211. this._vectors3[name] = value;
  65212. return this;
  65213. };
  65214. ProceduralTexture.prototype.setMatrix = function (name, value) {
  65215. this._checkUniform(name);
  65216. this._matrices[name] = value;
  65217. return this;
  65218. };
  65219. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65220. var scene = this.getScene();
  65221. if (!scene) {
  65222. return;
  65223. }
  65224. var engine = this._engine;
  65225. // Render
  65226. engine.enableEffect(this._effect);
  65227. engine.setState(false);
  65228. // Texture
  65229. for (var name in this._textures) {
  65230. this._effect.setTexture(name, this._textures[name]);
  65231. }
  65232. // Float
  65233. for (name in this._floats) {
  65234. this._effect.setFloat(name, this._floats[name]);
  65235. }
  65236. // Floats
  65237. for (name in this._floatsArrays) {
  65238. this._effect.setArray(name, this._floatsArrays[name]);
  65239. }
  65240. // Color3
  65241. for (name in this._colors3) {
  65242. this._effect.setColor3(name, this._colors3[name]);
  65243. }
  65244. // Color4
  65245. for (name in this._colors4) {
  65246. var color = this._colors4[name];
  65247. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  65248. }
  65249. // Vector2
  65250. for (name in this._vectors2) {
  65251. this._effect.setVector2(name, this._vectors2[name]);
  65252. }
  65253. // Vector3
  65254. for (name in this._vectors3) {
  65255. this._effect.setVector3(name, this._vectors3[name]);
  65256. }
  65257. // Matrix
  65258. for (name in this._matrices) {
  65259. this._effect.setMatrix(name, this._matrices[name]);
  65260. }
  65261. if (!this._texture) {
  65262. return;
  65263. }
  65264. if (this.isCube) {
  65265. for (var face = 0; face < 6; face++) {
  65266. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  65267. // VBOs
  65268. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65269. this._effect.setFloat("face", face);
  65270. // Clear
  65271. engine.clear(scene.clearColor, true, true, true);
  65272. // Draw order
  65273. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65274. // Mipmaps
  65275. if (face === 5) {
  65276. engine.generateMipMapsForCubemap(this._texture);
  65277. }
  65278. }
  65279. }
  65280. else {
  65281. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  65282. // VBOs
  65283. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65284. // Clear
  65285. engine.clear(scene.clearColor, true, true, true);
  65286. // Draw order
  65287. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65288. }
  65289. // Unbind
  65290. engine.unBindFramebuffer(this._texture, this.isCube);
  65291. if (this.onGenerated) {
  65292. this.onGenerated();
  65293. }
  65294. };
  65295. ProceduralTexture.prototype.clone = function () {
  65296. var textureSize = this.getSize();
  65297. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  65298. // Base texture
  65299. newTexture.hasAlpha = this.hasAlpha;
  65300. newTexture.level = this.level;
  65301. // RenderTarget Texture
  65302. newTexture.coordinatesMode = this.coordinatesMode;
  65303. return newTexture;
  65304. };
  65305. ProceduralTexture.prototype.dispose = function () {
  65306. var scene = this.getScene();
  65307. if (!scene) {
  65308. return;
  65309. }
  65310. var index = scene._proceduralTextures.indexOf(this);
  65311. if (index >= 0) {
  65312. scene._proceduralTextures.splice(index, 1);
  65313. }
  65314. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65315. if (vertexBuffer) {
  65316. vertexBuffer.dispose();
  65317. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65318. }
  65319. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  65320. this._indexBuffer = null;
  65321. }
  65322. _super.prototype.dispose.call(this);
  65323. };
  65324. return ProceduralTexture;
  65325. }(BABYLON.Texture));
  65326. BABYLON.ProceduralTexture = ProceduralTexture;
  65327. })(BABYLON || (BABYLON = {}));
  65328. //# sourceMappingURL=babylon.proceduralTexture.js.map
  65329. "use strict";
  65330. var BABYLON;
  65331. (function (BABYLON) {
  65332. var CustomProceduralTexture = /** @class */ (function (_super) {
  65333. __extends(CustomProceduralTexture, _super);
  65334. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  65335. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  65336. _this._animate = true;
  65337. _this._time = 0;
  65338. _this._texturePath = texturePath;
  65339. //Try to load json
  65340. _this.loadJson(texturePath);
  65341. _this.refreshRate = 1;
  65342. return _this;
  65343. }
  65344. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  65345. var _this = this;
  65346. var noConfigFile = function () {
  65347. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  65348. try {
  65349. _this.setFragment(_this._texturePath);
  65350. }
  65351. catch (ex) {
  65352. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  65353. }
  65354. };
  65355. var configFileUrl = jsonUrl + "/config.json";
  65356. var xhr = new XMLHttpRequest();
  65357. xhr.open("GET", configFileUrl, true);
  65358. xhr.addEventListener("load", function () {
  65359. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  65360. try {
  65361. _this._config = JSON.parse(xhr.response);
  65362. _this.updateShaderUniforms();
  65363. _this.updateTextures();
  65364. _this.setFragment(_this._texturePath + "/custom");
  65365. _this._animate = _this._config.animate;
  65366. _this.refreshRate = _this._config.refreshrate;
  65367. }
  65368. catch (ex) {
  65369. noConfigFile();
  65370. }
  65371. }
  65372. else {
  65373. noConfigFile();
  65374. }
  65375. }, false);
  65376. xhr.addEventListener("error", function () {
  65377. noConfigFile();
  65378. }, false);
  65379. try {
  65380. xhr.send();
  65381. }
  65382. catch (ex) {
  65383. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  65384. }
  65385. };
  65386. CustomProceduralTexture.prototype.isReady = function () {
  65387. if (!_super.prototype.isReady.call(this)) {
  65388. return false;
  65389. }
  65390. for (var name in this._textures) {
  65391. var texture = this._textures[name];
  65392. if (!texture.isReady()) {
  65393. return false;
  65394. }
  65395. }
  65396. return true;
  65397. };
  65398. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65399. var scene = this.getScene();
  65400. if (this._animate && scene) {
  65401. this._time += scene.getAnimationRatio() * 0.03;
  65402. this.updateShaderUniforms();
  65403. }
  65404. _super.prototype.render.call(this, useCameraPostProcess);
  65405. };
  65406. CustomProceduralTexture.prototype.updateTextures = function () {
  65407. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  65408. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  65409. }
  65410. };
  65411. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  65412. if (this._config) {
  65413. for (var j = 0; j < this._config.uniforms.length; j++) {
  65414. var uniform = this._config.uniforms[j];
  65415. switch (uniform.type) {
  65416. case "float":
  65417. this.setFloat(uniform.name, uniform.value);
  65418. break;
  65419. case "color3":
  65420. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  65421. break;
  65422. case "color4":
  65423. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  65424. break;
  65425. case "vector2":
  65426. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  65427. break;
  65428. case "vector3":
  65429. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  65430. break;
  65431. }
  65432. }
  65433. }
  65434. this.setFloat("time", this._time);
  65435. };
  65436. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  65437. get: function () {
  65438. return this._animate;
  65439. },
  65440. set: function (value) {
  65441. this._animate = value;
  65442. },
  65443. enumerable: true,
  65444. configurable: true
  65445. });
  65446. return CustomProceduralTexture;
  65447. }(BABYLON.ProceduralTexture));
  65448. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  65449. })(BABYLON || (BABYLON = {}));
  65450. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  65451. "use strict";
  65452. var BABYLON;
  65453. (function (BABYLON) {
  65454. var FreeCameraGamepadInput = /** @class */ (function () {
  65455. function FreeCameraGamepadInput() {
  65456. this.gamepadAngularSensibility = 200;
  65457. this.gamepadMoveSensibility = 40;
  65458. // private members
  65459. this._cameraTransform = BABYLON.Matrix.Identity();
  65460. this._deltaTransform = BABYLON.Vector3.Zero();
  65461. this._vector3 = BABYLON.Vector3.Zero();
  65462. this._vector2 = BABYLON.Vector2.Zero();
  65463. }
  65464. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65465. var _this = this;
  65466. var manager = this.camera.getScene().gamepadManager;
  65467. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65468. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65469. // prioritize XBOX gamepads.
  65470. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65471. _this.gamepad = gamepad;
  65472. }
  65473. }
  65474. });
  65475. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65476. if (_this.gamepad === gamepad) {
  65477. _this.gamepad = null;
  65478. }
  65479. });
  65480. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65481. };
  65482. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  65483. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65484. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65485. this.gamepad = null;
  65486. };
  65487. FreeCameraGamepadInput.prototype.checkInputs = function () {
  65488. if (this.gamepad && this.gamepad.leftStick) {
  65489. var camera = this.camera;
  65490. var LSValues = this.gamepad.leftStick;
  65491. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  65492. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65493. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  65494. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  65495. var RSValues = this.gamepad.rightStick;
  65496. if (RSValues) {
  65497. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  65498. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  65499. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  65500. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  65501. }
  65502. else {
  65503. RSValues = { x: 0, y: 0 };
  65504. }
  65505. if (!camera.rotationQuaternion) {
  65506. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  65507. }
  65508. else {
  65509. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  65510. }
  65511. var speed = camera._computeLocalCameraSpeed() * 50.0;
  65512. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  65513. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  65514. camera.cameraDirection.addInPlace(this._deltaTransform);
  65515. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  65516. camera.cameraRotation.addInPlace(this._vector2);
  65517. }
  65518. };
  65519. FreeCameraGamepadInput.prototype.getClassName = function () {
  65520. return "FreeCameraGamepadInput";
  65521. };
  65522. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  65523. return "gamepad";
  65524. };
  65525. __decorate([
  65526. BABYLON.serialize()
  65527. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  65528. __decorate([
  65529. BABYLON.serialize()
  65530. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65531. return FreeCameraGamepadInput;
  65532. }());
  65533. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  65534. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  65535. })(BABYLON || (BABYLON = {}));
  65536. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  65537. "use strict";
  65538. var BABYLON;
  65539. (function (BABYLON) {
  65540. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  65541. function ArcRotateCameraGamepadInput() {
  65542. this.gamepadRotationSensibility = 80;
  65543. this.gamepadMoveSensibility = 40;
  65544. }
  65545. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65546. var _this = this;
  65547. var manager = this.camera.getScene().gamepadManager;
  65548. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65549. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65550. // prioritize XBOX gamepads.
  65551. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65552. _this.gamepad = gamepad;
  65553. }
  65554. }
  65555. });
  65556. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65557. if (_this.gamepad === gamepad) {
  65558. _this.gamepad = null;
  65559. }
  65560. });
  65561. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65562. };
  65563. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  65564. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65565. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65566. this.gamepad = null;
  65567. };
  65568. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  65569. if (this.gamepad) {
  65570. var camera = this.camera;
  65571. var RSValues = this.gamepad.rightStick;
  65572. if (RSValues) {
  65573. if (RSValues.x != 0) {
  65574. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  65575. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  65576. camera.inertialAlphaOffset += normalizedRX;
  65577. }
  65578. }
  65579. if (RSValues.y != 0) {
  65580. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  65581. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  65582. camera.inertialBetaOffset += normalizedRY;
  65583. }
  65584. }
  65585. }
  65586. var LSValues = this.gamepad.leftStick;
  65587. if (LSValues && LSValues.y != 0) {
  65588. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65589. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  65590. this.camera.inertialRadiusOffset -= normalizedLY;
  65591. }
  65592. }
  65593. }
  65594. };
  65595. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  65596. return "ArcRotateCameraGamepadInput";
  65597. };
  65598. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  65599. return "gamepad";
  65600. };
  65601. __decorate([
  65602. BABYLON.serialize()
  65603. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  65604. __decorate([
  65605. BABYLON.serialize()
  65606. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65607. return ArcRotateCameraGamepadInput;
  65608. }());
  65609. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  65610. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  65611. })(BABYLON || (BABYLON = {}));
  65612. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  65613. "use strict";
  65614. var BABYLON;
  65615. (function (BABYLON) {
  65616. var GamepadManager = /** @class */ (function () {
  65617. function GamepadManager(_scene) {
  65618. var _this = this;
  65619. this._scene = _scene;
  65620. this._babylonGamepads = [];
  65621. this._oneGamepadConnected = false;
  65622. this._isMonitoring = false;
  65623. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  65624. if (!BABYLON.Tools.IsWindowObjectExist()) {
  65625. this._gamepadEventSupported = false;
  65626. }
  65627. else {
  65628. this._gamepadEventSupported = 'GamepadEvent' in window;
  65629. this._gamepadSupport = (navigator.getGamepads ||
  65630. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  65631. }
  65632. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  65633. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  65634. for (var i in _this._babylonGamepads) {
  65635. var gamepad = _this._babylonGamepads[i];
  65636. if (gamepad && gamepad._isConnected) {
  65637. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  65638. }
  65639. }
  65640. });
  65641. this._onGamepadConnectedEvent = function (evt) {
  65642. var gamepad = evt.gamepad;
  65643. if (gamepad.index in _this._babylonGamepads) {
  65644. if (_this._babylonGamepads[gamepad.index].isConnected) {
  65645. return;
  65646. }
  65647. }
  65648. var newGamepad;
  65649. if (_this._babylonGamepads[gamepad.index]) {
  65650. newGamepad = _this._babylonGamepads[gamepad.index];
  65651. newGamepad.browserGamepad = gamepad;
  65652. newGamepad._isConnected = true;
  65653. }
  65654. else {
  65655. newGamepad = _this._addNewGamepad(gamepad);
  65656. }
  65657. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65658. _this._startMonitoringGamepads();
  65659. };
  65660. this._onGamepadDisconnectedEvent = function (evt) {
  65661. var gamepad = evt.gamepad;
  65662. // Remove the gamepad from the list of gamepads to monitor.
  65663. for (var i in _this._babylonGamepads) {
  65664. if (_this._babylonGamepads[i].index === gamepad.index) {
  65665. var disconnectedGamepad = _this._babylonGamepads[i];
  65666. disconnectedGamepad._isConnected = false;
  65667. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  65668. break;
  65669. }
  65670. }
  65671. };
  65672. if (this._gamepadSupport) {
  65673. //first add already-connected gamepads
  65674. this._updateGamepadObjects();
  65675. if (this._babylonGamepads.length) {
  65676. this._startMonitoringGamepads();
  65677. }
  65678. // Checking if the gamepad connected event is supported (like in Firefox)
  65679. if (this._gamepadEventSupported) {
  65680. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  65681. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  65682. }
  65683. else {
  65684. this._startMonitoringGamepads();
  65685. }
  65686. }
  65687. }
  65688. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  65689. get: function () {
  65690. return this._babylonGamepads;
  65691. },
  65692. enumerable: true,
  65693. configurable: true
  65694. });
  65695. GamepadManager.prototype.getGamepadByType = function (type) {
  65696. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  65697. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  65698. var gamepad = _a[_i];
  65699. if (gamepad && gamepad.type === type) {
  65700. return gamepad;
  65701. }
  65702. }
  65703. return null;
  65704. };
  65705. GamepadManager.prototype.dispose = function () {
  65706. if (this._gamepadEventSupported) {
  65707. if (this._onGamepadConnectedEvent) {
  65708. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  65709. }
  65710. if (this._onGamepadDisconnectedEvent) {
  65711. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  65712. }
  65713. this._onGamepadConnectedEvent = null;
  65714. this._onGamepadDisconnectedEvent = null;
  65715. }
  65716. this._babylonGamepads.forEach(function (gamepad) {
  65717. gamepad.dispose();
  65718. });
  65719. this.onGamepadConnectedObservable.clear();
  65720. this.onGamepadDisconnectedObservable.clear();
  65721. this._oneGamepadConnected = false;
  65722. this._stopMonitoringGamepads();
  65723. this._babylonGamepads = [];
  65724. };
  65725. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  65726. if (!this._oneGamepadConnected) {
  65727. this._oneGamepadConnected = true;
  65728. }
  65729. var newGamepad;
  65730. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  65731. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  65732. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  65733. }
  65734. else if (gamepad.pose) {
  65735. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  65736. }
  65737. else {
  65738. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  65739. }
  65740. this._babylonGamepads[newGamepad.index] = newGamepad;
  65741. return newGamepad;
  65742. };
  65743. GamepadManager.prototype._startMonitoringGamepads = function () {
  65744. if (!this._isMonitoring) {
  65745. this._isMonitoring = true;
  65746. //back-comp
  65747. if (!this._scene) {
  65748. this._checkGamepadsStatus();
  65749. }
  65750. }
  65751. };
  65752. GamepadManager.prototype._stopMonitoringGamepads = function () {
  65753. this._isMonitoring = false;
  65754. };
  65755. GamepadManager.prototype._checkGamepadsStatus = function () {
  65756. var _this = this;
  65757. // Hack to be compatible Chrome
  65758. this._updateGamepadObjects();
  65759. for (var i in this._babylonGamepads) {
  65760. var gamepad = this._babylonGamepads[i];
  65761. if (!gamepad || !gamepad.isConnected) {
  65762. continue;
  65763. }
  65764. gamepad.update();
  65765. }
  65766. if (this._isMonitoring && !this._scene) {
  65767. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  65768. }
  65769. };
  65770. // This function is called only on Chrome, which does not properly support
  65771. // connection/disconnection events and forces you to recopy again the gamepad object
  65772. GamepadManager.prototype._updateGamepadObjects = function () {
  65773. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  65774. for (var i = 0; i < gamepads.length; i++) {
  65775. if (gamepads[i]) {
  65776. if (!this._babylonGamepads[gamepads[i].index]) {
  65777. var newGamepad = this._addNewGamepad(gamepads[i]);
  65778. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65779. }
  65780. else {
  65781. // Forced to copy again this object for Chrome for unknown reason
  65782. this._babylonGamepads[i].browserGamepad = gamepads[i];
  65783. if (!this._babylonGamepads[i].isConnected) {
  65784. this._babylonGamepads[i]._isConnected = true;
  65785. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  65786. }
  65787. }
  65788. }
  65789. }
  65790. };
  65791. return GamepadManager;
  65792. }());
  65793. BABYLON.GamepadManager = GamepadManager;
  65794. })(BABYLON || (BABYLON = {}));
  65795. //# sourceMappingURL=babylon.gamepadManager.js.map
  65796. "use strict";
  65797. var BABYLON;
  65798. (function (BABYLON) {
  65799. var StickValues = /** @class */ (function () {
  65800. function StickValues(x, y) {
  65801. this.x = x;
  65802. this.y = y;
  65803. }
  65804. return StickValues;
  65805. }());
  65806. BABYLON.StickValues = StickValues;
  65807. var Gamepad = /** @class */ (function () {
  65808. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  65809. if (leftStickX === void 0) { leftStickX = 0; }
  65810. if (leftStickY === void 0) { leftStickY = 1; }
  65811. if (rightStickX === void 0) { rightStickX = 2; }
  65812. if (rightStickY === void 0) { rightStickY = 3; }
  65813. this.id = id;
  65814. this.index = index;
  65815. this.browserGamepad = browserGamepad;
  65816. this._isConnected = true;
  65817. this._invertLeftStickY = false;
  65818. this.type = Gamepad.GAMEPAD;
  65819. this._leftStickAxisX = leftStickX;
  65820. this._leftStickAxisY = leftStickY;
  65821. this._rightStickAxisX = rightStickX;
  65822. this._rightStickAxisY = rightStickY;
  65823. if (this.browserGamepad.axes.length >= 2) {
  65824. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65825. }
  65826. if (this.browserGamepad.axes.length >= 4) {
  65827. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65828. }
  65829. }
  65830. Object.defineProperty(Gamepad.prototype, "isConnected", {
  65831. get: function () {
  65832. return this._isConnected;
  65833. },
  65834. enumerable: true,
  65835. configurable: true
  65836. });
  65837. Gamepad.prototype.onleftstickchanged = function (callback) {
  65838. this._onleftstickchanged = callback;
  65839. };
  65840. Gamepad.prototype.onrightstickchanged = function (callback) {
  65841. this._onrightstickchanged = callback;
  65842. };
  65843. Object.defineProperty(Gamepad.prototype, "leftStick", {
  65844. get: function () {
  65845. return this._leftStick;
  65846. },
  65847. set: function (newValues) {
  65848. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  65849. this._onleftstickchanged(newValues);
  65850. }
  65851. this._leftStick = newValues;
  65852. },
  65853. enumerable: true,
  65854. configurable: true
  65855. });
  65856. Object.defineProperty(Gamepad.prototype, "rightStick", {
  65857. get: function () {
  65858. return this._rightStick;
  65859. },
  65860. set: function (newValues) {
  65861. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  65862. this._onrightstickchanged(newValues);
  65863. }
  65864. this._rightStick = newValues;
  65865. },
  65866. enumerable: true,
  65867. configurable: true
  65868. });
  65869. Gamepad.prototype.update = function () {
  65870. if (this._leftStick) {
  65871. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65872. if (this._invertLeftStickY) {
  65873. this.leftStick.y *= -1;
  65874. }
  65875. }
  65876. if (this._rightStick) {
  65877. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65878. }
  65879. };
  65880. Gamepad.prototype.dispose = function () {
  65881. };
  65882. Gamepad.GAMEPAD = 0;
  65883. Gamepad.GENERIC = 1;
  65884. Gamepad.XBOX = 2;
  65885. Gamepad.POSE_ENABLED = 3;
  65886. return Gamepad;
  65887. }());
  65888. BABYLON.Gamepad = Gamepad;
  65889. var GenericPad = /** @class */ (function (_super) {
  65890. __extends(GenericPad, _super);
  65891. function GenericPad(id, index, browserGamepad) {
  65892. var _this = _super.call(this, id, index, browserGamepad) || this;
  65893. _this.onButtonDownObservable = new BABYLON.Observable();
  65894. _this.onButtonUpObservable = new BABYLON.Observable();
  65895. _this.type = Gamepad.GENERIC;
  65896. _this._buttons = new Array(browserGamepad.buttons.length);
  65897. return _this;
  65898. }
  65899. GenericPad.prototype.onbuttondown = function (callback) {
  65900. this._onbuttondown = callback;
  65901. };
  65902. GenericPad.prototype.onbuttonup = function (callback) {
  65903. this._onbuttonup = callback;
  65904. };
  65905. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  65906. if (newValue !== currentValue) {
  65907. if (newValue === 1) {
  65908. if (this._onbuttondown) {
  65909. this._onbuttondown(buttonIndex);
  65910. }
  65911. this.onButtonDownObservable.notifyObservers(buttonIndex);
  65912. }
  65913. if (newValue === 0) {
  65914. if (this._onbuttonup) {
  65915. this._onbuttonup(buttonIndex);
  65916. }
  65917. this.onButtonUpObservable.notifyObservers(buttonIndex);
  65918. }
  65919. }
  65920. return newValue;
  65921. };
  65922. GenericPad.prototype.update = function () {
  65923. _super.prototype.update.call(this);
  65924. for (var index = 0; index < this._buttons.length; index++) {
  65925. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  65926. }
  65927. };
  65928. GenericPad.prototype.dispose = function () {
  65929. _super.prototype.dispose.call(this);
  65930. this.onButtonDownObservable.clear();
  65931. this.onButtonUpObservable.clear();
  65932. };
  65933. return GenericPad;
  65934. }(Gamepad));
  65935. BABYLON.GenericPad = GenericPad;
  65936. })(BABYLON || (BABYLON = {}));
  65937. //# sourceMappingURL=babylon.gamepad.js.map
  65938. "use strict";
  65939. var BABYLON;
  65940. (function (BABYLON) {
  65941. var Xbox360Button;
  65942. (function (Xbox360Button) {
  65943. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  65944. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  65945. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  65946. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  65947. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  65948. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  65949. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  65950. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  65951. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  65952. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  65953. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  65954. var Xbox360Dpad;
  65955. (function (Xbox360Dpad) {
  65956. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  65957. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  65958. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  65959. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  65960. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  65961. var Xbox360Pad = /** @class */ (function (_super) {
  65962. __extends(Xbox360Pad, _super);
  65963. function Xbox360Pad(id, index, gamepad, xboxOne) {
  65964. if (xboxOne === void 0) { xboxOne = false; }
  65965. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  65966. _this._leftTrigger = 0;
  65967. _this._rightTrigger = 0;
  65968. _this.onButtonDownObservable = new BABYLON.Observable();
  65969. _this.onButtonUpObservable = new BABYLON.Observable();
  65970. _this.onPadDownObservable = new BABYLON.Observable();
  65971. _this.onPadUpObservable = new BABYLON.Observable();
  65972. _this._buttonA = 0;
  65973. _this._buttonB = 0;
  65974. _this._buttonX = 0;
  65975. _this._buttonY = 0;
  65976. _this._buttonBack = 0;
  65977. _this._buttonStart = 0;
  65978. _this._buttonLB = 0;
  65979. _this._buttonRB = 0;
  65980. _this._buttonLeftStick = 0;
  65981. _this._buttonRightStick = 0;
  65982. _this._dPadUp = 0;
  65983. _this._dPadDown = 0;
  65984. _this._dPadLeft = 0;
  65985. _this._dPadRight = 0;
  65986. _this._isXboxOnePad = false;
  65987. _this.type = BABYLON.Gamepad.XBOX;
  65988. _this._isXboxOnePad = xboxOne;
  65989. return _this;
  65990. }
  65991. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  65992. this._onlefttriggerchanged = callback;
  65993. };
  65994. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  65995. this._onrighttriggerchanged = callback;
  65996. };
  65997. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  65998. get: function () {
  65999. return this._leftTrigger;
  66000. },
  66001. set: function (newValue) {
  66002. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  66003. this._onlefttriggerchanged(newValue);
  66004. }
  66005. this._leftTrigger = newValue;
  66006. },
  66007. enumerable: true,
  66008. configurable: true
  66009. });
  66010. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  66011. get: function () {
  66012. return this._rightTrigger;
  66013. },
  66014. set: function (newValue) {
  66015. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  66016. this._onrighttriggerchanged(newValue);
  66017. }
  66018. this._rightTrigger = newValue;
  66019. },
  66020. enumerable: true,
  66021. configurable: true
  66022. });
  66023. Xbox360Pad.prototype.onbuttondown = function (callback) {
  66024. this._onbuttondown = callback;
  66025. };
  66026. Xbox360Pad.prototype.onbuttonup = function (callback) {
  66027. this._onbuttonup = callback;
  66028. };
  66029. Xbox360Pad.prototype.ondpaddown = function (callback) {
  66030. this._ondpaddown = callback;
  66031. };
  66032. Xbox360Pad.prototype.ondpadup = function (callback) {
  66033. this._ondpadup = callback;
  66034. };
  66035. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  66036. if (newValue !== currentValue) {
  66037. if (newValue === 1) {
  66038. if (this._onbuttondown) {
  66039. this._onbuttondown(buttonType);
  66040. }
  66041. this.onButtonDownObservable.notifyObservers(buttonType);
  66042. }
  66043. if (newValue === 0) {
  66044. if (this._onbuttonup) {
  66045. this._onbuttonup(buttonType);
  66046. }
  66047. this.onButtonUpObservable.notifyObservers(buttonType);
  66048. }
  66049. }
  66050. return newValue;
  66051. };
  66052. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  66053. if (newValue !== currentValue) {
  66054. if (newValue === 1) {
  66055. if (this._ondpaddown) {
  66056. this._ondpaddown(buttonType);
  66057. }
  66058. this.onPadDownObservable.notifyObservers(buttonType);
  66059. }
  66060. if (newValue === 0) {
  66061. if (this._ondpadup) {
  66062. this._ondpadup(buttonType);
  66063. }
  66064. this.onPadUpObservable.notifyObservers(buttonType);
  66065. }
  66066. }
  66067. return newValue;
  66068. };
  66069. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  66070. get: function () {
  66071. return this._buttonA;
  66072. },
  66073. set: function (value) {
  66074. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  66075. },
  66076. enumerable: true,
  66077. configurable: true
  66078. });
  66079. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  66080. get: function () {
  66081. return this._buttonB;
  66082. },
  66083. set: function (value) {
  66084. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  66085. },
  66086. enumerable: true,
  66087. configurable: true
  66088. });
  66089. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  66090. get: function () {
  66091. return this._buttonX;
  66092. },
  66093. set: function (value) {
  66094. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  66095. },
  66096. enumerable: true,
  66097. configurable: true
  66098. });
  66099. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  66100. get: function () {
  66101. return this._buttonY;
  66102. },
  66103. set: function (value) {
  66104. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  66105. },
  66106. enumerable: true,
  66107. configurable: true
  66108. });
  66109. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  66110. get: function () {
  66111. return this._buttonStart;
  66112. },
  66113. set: function (value) {
  66114. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  66115. },
  66116. enumerable: true,
  66117. configurable: true
  66118. });
  66119. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  66120. get: function () {
  66121. return this._buttonBack;
  66122. },
  66123. set: function (value) {
  66124. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  66125. },
  66126. enumerable: true,
  66127. configurable: true
  66128. });
  66129. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  66130. get: function () {
  66131. return this._buttonLB;
  66132. },
  66133. set: function (value) {
  66134. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  66135. },
  66136. enumerable: true,
  66137. configurable: true
  66138. });
  66139. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  66140. get: function () {
  66141. return this._buttonRB;
  66142. },
  66143. set: function (value) {
  66144. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  66145. },
  66146. enumerable: true,
  66147. configurable: true
  66148. });
  66149. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  66150. get: function () {
  66151. return this._buttonLeftStick;
  66152. },
  66153. set: function (value) {
  66154. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  66155. },
  66156. enumerable: true,
  66157. configurable: true
  66158. });
  66159. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  66160. get: function () {
  66161. return this._buttonRightStick;
  66162. },
  66163. set: function (value) {
  66164. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  66165. },
  66166. enumerable: true,
  66167. configurable: true
  66168. });
  66169. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  66170. get: function () {
  66171. return this._dPadUp;
  66172. },
  66173. set: function (value) {
  66174. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  66175. },
  66176. enumerable: true,
  66177. configurable: true
  66178. });
  66179. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  66180. get: function () {
  66181. return this._dPadDown;
  66182. },
  66183. set: function (value) {
  66184. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  66185. },
  66186. enumerable: true,
  66187. configurable: true
  66188. });
  66189. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  66190. get: function () {
  66191. return this._dPadLeft;
  66192. },
  66193. set: function (value) {
  66194. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  66195. },
  66196. enumerable: true,
  66197. configurable: true
  66198. });
  66199. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  66200. get: function () {
  66201. return this._dPadRight;
  66202. },
  66203. set: function (value) {
  66204. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  66205. },
  66206. enumerable: true,
  66207. configurable: true
  66208. });
  66209. Xbox360Pad.prototype.update = function () {
  66210. _super.prototype.update.call(this);
  66211. if (this._isXboxOnePad) {
  66212. this.buttonA = this.browserGamepad.buttons[0].value;
  66213. this.buttonB = this.browserGamepad.buttons[1].value;
  66214. this.buttonX = this.browserGamepad.buttons[2].value;
  66215. this.buttonY = this.browserGamepad.buttons[3].value;
  66216. this.buttonLB = this.browserGamepad.buttons[4].value;
  66217. this.buttonRB = this.browserGamepad.buttons[5].value;
  66218. this.leftTrigger = this.browserGamepad.axes[2];
  66219. this.rightTrigger = this.browserGamepad.axes[5];
  66220. this.buttonBack = this.browserGamepad.buttons[9].value;
  66221. this.buttonStart = this.browserGamepad.buttons[8].value;
  66222. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  66223. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  66224. this.dPadUp = this.browserGamepad.buttons[11].value;
  66225. this.dPadDown = this.browserGamepad.buttons[12].value;
  66226. this.dPadLeft = this.browserGamepad.buttons[13].value;
  66227. this.dPadRight = this.browserGamepad.buttons[14].value;
  66228. }
  66229. else {
  66230. this.buttonA = this.browserGamepad.buttons[0].value;
  66231. this.buttonB = this.browserGamepad.buttons[1].value;
  66232. this.buttonX = this.browserGamepad.buttons[2].value;
  66233. this.buttonY = this.browserGamepad.buttons[3].value;
  66234. this.buttonLB = this.browserGamepad.buttons[4].value;
  66235. this.buttonRB = this.browserGamepad.buttons[5].value;
  66236. this.leftTrigger = this.browserGamepad.buttons[6].value;
  66237. this.rightTrigger = this.browserGamepad.buttons[7].value;
  66238. this.buttonBack = this.browserGamepad.buttons[8].value;
  66239. this.buttonStart = this.browserGamepad.buttons[9].value;
  66240. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  66241. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  66242. this.dPadUp = this.browserGamepad.buttons[12].value;
  66243. this.dPadDown = this.browserGamepad.buttons[13].value;
  66244. this.dPadLeft = this.browserGamepad.buttons[14].value;
  66245. this.dPadRight = this.browserGamepad.buttons[15].value;
  66246. }
  66247. };
  66248. Xbox360Pad.prototype.dispose = function () {
  66249. _super.prototype.dispose.call(this);
  66250. this.onButtonDownObservable.clear();
  66251. this.onButtonUpObservable.clear();
  66252. this.onPadDownObservable.clear();
  66253. this.onPadUpObservable.clear();
  66254. };
  66255. return Xbox360Pad;
  66256. }(BABYLON.Gamepad));
  66257. BABYLON.Xbox360Pad = Xbox360Pad;
  66258. })(BABYLON || (BABYLON = {}));
  66259. //# sourceMappingURL=babylon.xboxGamepad.js.map
  66260. "use strict";
  66261. var BABYLON;
  66262. (function (BABYLON) {
  66263. var PoseEnabledControllerType;
  66264. (function (PoseEnabledControllerType) {
  66265. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  66266. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  66267. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  66268. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  66269. /**
  66270. * Google Daydream
  66271. */
  66272. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  66273. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  66274. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  66275. var PoseEnabledControllerHelper = /** @class */ (function () {
  66276. function PoseEnabledControllerHelper() {
  66277. }
  66278. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  66279. // Oculus Touch
  66280. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  66281. return new BABYLON.OculusTouchController(vrGamepad);
  66282. }
  66283. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  66284. return new BABYLON.WindowsMotionController(vrGamepad);
  66285. }
  66286. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  66287. return new BABYLON.ViveController(vrGamepad);
  66288. }
  66289. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  66290. return new BABYLON.GearVRController(vrGamepad);
  66291. }
  66292. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  66293. return new BABYLON.DaydreamController(vrGamepad);
  66294. }
  66295. else {
  66296. return new BABYLON.GenericController(vrGamepad);
  66297. }
  66298. };
  66299. return PoseEnabledControllerHelper;
  66300. }());
  66301. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  66302. var PoseEnabledController = /** @class */ (function (_super) {
  66303. __extends(PoseEnabledController, _super);
  66304. function PoseEnabledController(browserGamepad) {
  66305. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  66306. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  66307. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  66308. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  66309. // Represents device position and rotation in babylon space
  66310. _this.devicePosition = BABYLON.Vector3.Zero();
  66311. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  66312. _this.deviceScaleFactor = 1;
  66313. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  66314. _this._deviceToWorld = BABYLON.Matrix.Identity();
  66315. /**
  66316. * Node to be used when casting a ray from the controller
  66317. */
  66318. _this._pointingPoseNode = null;
  66319. _this._workingMatrix = BABYLON.Matrix.Identity();
  66320. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  66321. _this.controllerType = PoseEnabledControllerType.GENERIC;
  66322. _this.position = BABYLON.Vector3.Zero();
  66323. _this.rotationQuaternion = new BABYLON.Quaternion();
  66324. _this._calculatedPosition = BABYLON.Vector3.Zero();
  66325. _this._calculatedRotation = new BABYLON.Quaternion();
  66326. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  66327. return _this;
  66328. }
  66329. PoseEnabledController.prototype.update = function () {
  66330. _super.prototype.update.call(this);
  66331. var pose = this.browserGamepad.pose;
  66332. this.updateFromDevice(pose);
  66333. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  66334. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  66335. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  66336. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  66337. if (this._mesh) {
  66338. this._mesh.position.copyFrom(this.devicePosition);
  66339. if (this._mesh.rotationQuaternion) {
  66340. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66341. }
  66342. }
  66343. };
  66344. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  66345. if (poseData) {
  66346. this.rawPose = poseData;
  66347. if (poseData.position) {
  66348. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  66349. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  66350. this._deviceRoomPosition.z *= -1;
  66351. }
  66352. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  66353. this._calculatedPosition.addInPlace(this.position);
  66354. }
  66355. var pose = this.rawPose;
  66356. if (poseData.orientation && pose.orientation) {
  66357. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  66358. if (this._mesh) {
  66359. if (this._mesh.getScene().useRightHandedSystem) {
  66360. this._deviceRoomRotationQuaternion.z *= -1;
  66361. this._deviceRoomRotationQuaternion.w *= -1;
  66362. }
  66363. else {
  66364. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  66365. }
  66366. }
  66367. // if the camera is set, rotate to the camera's rotation
  66368. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  66369. }
  66370. }
  66371. };
  66372. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  66373. if (this._mesh) {
  66374. this._mesh.parent = null;
  66375. }
  66376. this._mesh = mesh;
  66377. if (this._poseControlledCamera) {
  66378. this._mesh.parent = this._poseControlledCamera;
  66379. }
  66380. if (!this._mesh.rotationQuaternion) {
  66381. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  66382. }
  66383. };
  66384. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  66385. this._poseControlledCamera = camera;
  66386. if (this._mesh) {
  66387. this._mesh.parent = this._poseControlledCamera;
  66388. }
  66389. };
  66390. PoseEnabledController.prototype.dispose = function () {
  66391. if (this._mesh) {
  66392. this._mesh.dispose();
  66393. }
  66394. this._mesh = null;
  66395. _super.prototype.dispose.call(this);
  66396. };
  66397. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  66398. get: function () {
  66399. return this._mesh;
  66400. },
  66401. enumerable: true,
  66402. configurable: true
  66403. });
  66404. PoseEnabledController.prototype.getForwardRay = function (length) {
  66405. if (length === void 0) { length = 100; }
  66406. if (!this.mesh) {
  66407. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  66408. }
  66409. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  66410. var origin = m.getTranslation();
  66411. var forward = new BABYLON.Vector3(0, 0, -1);
  66412. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66413. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66414. return new BABYLON.Ray(origin, direction, length);
  66415. };
  66416. /**
  66417. * Name of the child mesh that can be used to cast a ray from the controller
  66418. */
  66419. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  66420. return PoseEnabledController;
  66421. }(BABYLON.Gamepad));
  66422. BABYLON.PoseEnabledController = PoseEnabledController;
  66423. })(BABYLON || (BABYLON = {}));
  66424. //# sourceMappingURL=babylon.poseEnabledController.js.map
  66425. "use strict";
  66426. var BABYLON;
  66427. (function (BABYLON) {
  66428. var WebVRController = /** @class */ (function (_super) {
  66429. __extends(WebVRController, _super);
  66430. function WebVRController(vrGamepad) {
  66431. var _this = _super.call(this, vrGamepad) || this;
  66432. // Observables
  66433. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  66434. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  66435. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  66436. _this.onPadStateChangedObservable = new BABYLON.Observable();
  66437. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  66438. _this.pad = { x: 0, y: 0 };
  66439. // avoid GC, store state in a tmp object
  66440. _this._changes = {
  66441. pressChanged: false,
  66442. touchChanged: false,
  66443. valueChanged: false,
  66444. changed: false
  66445. };
  66446. _this._buttons = new Array(vrGamepad.buttons.length);
  66447. _this.hand = vrGamepad.hand;
  66448. return _this;
  66449. }
  66450. WebVRController.prototype.onButtonStateChange = function (callback) {
  66451. this._onButtonStateChange = callback;
  66452. };
  66453. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  66454. get: function () {
  66455. return this._defaultModel;
  66456. },
  66457. enumerable: true,
  66458. configurable: true
  66459. });
  66460. WebVRController.prototype.update = function () {
  66461. _super.prototype.update.call(this);
  66462. for (var index = 0; index < this._buttons.length; index++) {
  66463. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  66464. }
  66465. ;
  66466. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  66467. this.pad.x = this.leftStick.x;
  66468. this.pad.y = this.leftStick.y;
  66469. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  66470. }
  66471. };
  66472. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  66473. if (!newState) {
  66474. newState = {
  66475. pressed: false,
  66476. touched: false,
  66477. value: 0
  66478. };
  66479. }
  66480. if (!currentState) {
  66481. this._buttons[buttonIndex] = {
  66482. pressed: newState.pressed,
  66483. touched: newState.touched,
  66484. value: newState.value
  66485. };
  66486. return;
  66487. }
  66488. this._checkChanges(newState, currentState);
  66489. if (this._changes.changed) {
  66490. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  66491. this._handleButtonChange(buttonIndex, newState, this._changes);
  66492. }
  66493. this._buttons[buttonIndex].pressed = newState.pressed;
  66494. this._buttons[buttonIndex].touched = newState.touched;
  66495. // oculus triggers are never 0, thou not touched.
  66496. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  66497. };
  66498. WebVRController.prototype._checkChanges = function (newState, currentState) {
  66499. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  66500. this._changes.touchChanged = newState.touched !== currentState.touched;
  66501. this._changes.valueChanged = newState.value !== currentState.value;
  66502. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  66503. return this._changes;
  66504. };
  66505. WebVRController.prototype.dispose = function () {
  66506. _super.prototype.dispose.call(this);
  66507. this.onTriggerStateChangedObservable.clear();
  66508. this.onMainButtonStateChangedObservable.clear();
  66509. this.onSecondaryButtonStateChangedObservable.clear();
  66510. this.onPadStateChangedObservable.clear();
  66511. this.onPadValuesChangedObservable.clear();
  66512. };
  66513. return WebVRController;
  66514. }(BABYLON.PoseEnabledController));
  66515. BABYLON.WebVRController = WebVRController;
  66516. })(BABYLON || (BABYLON = {}));
  66517. //# sourceMappingURL=babylon.webVRController.js.map
  66518. "use strict";
  66519. var BABYLON;
  66520. (function (BABYLON) {
  66521. var OculusTouchController = /** @class */ (function (_super) {
  66522. __extends(OculusTouchController, _super);
  66523. function OculusTouchController(vrGamepad) {
  66524. var _this = _super.call(this, vrGamepad) || this;
  66525. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  66526. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  66527. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  66528. return _this;
  66529. }
  66530. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66531. var _this = this;
  66532. var meshName;
  66533. // Hand
  66534. if (this.hand === 'left') {
  66535. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  66536. }
  66537. else {
  66538. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  66539. }
  66540. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  66541. /*
  66542. Parent Mesh name: oculus_touch_left
  66543. - body
  66544. - trigger
  66545. - thumbstick
  66546. - grip
  66547. - button_y
  66548. - button_x
  66549. - button_enter
  66550. */
  66551. _this._defaultModel = newMeshes[1];
  66552. _this.attachToMesh(_this._defaultModel);
  66553. if (meshLoaded) {
  66554. meshLoaded(_this._defaultModel);
  66555. }
  66556. });
  66557. };
  66558. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  66559. // helper getters for left and right hand.
  66560. get: function () {
  66561. if (this.hand === 'right') {
  66562. return this.onMainButtonStateChangedObservable;
  66563. }
  66564. else {
  66565. throw new Error('No A button on left hand');
  66566. }
  66567. },
  66568. enumerable: true,
  66569. configurable: true
  66570. });
  66571. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  66572. get: function () {
  66573. if (this.hand === 'right') {
  66574. return this.onSecondaryButtonStateChangedObservable;
  66575. }
  66576. else {
  66577. throw new Error('No B button on left hand');
  66578. }
  66579. },
  66580. enumerable: true,
  66581. configurable: true
  66582. });
  66583. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  66584. get: function () {
  66585. if (this.hand === 'left') {
  66586. return this.onMainButtonStateChangedObservable;
  66587. }
  66588. else {
  66589. throw new Error('No X button on right hand');
  66590. }
  66591. },
  66592. enumerable: true,
  66593. configurable: true
  66594. });
  66595. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  66596. get: function () {
  66597. if (this.hand === 'left') {
  66598. return this.onSecondaryButtonStateChangedObservable;
  66599. }
  66600. else {
  66601. throw new Error('No Y button on right hand');
  66602. }
  66603. },
  66604. enumerable: true,
  66605. configurable: true
  66606. });
  66607. /*
  66608. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  66609. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  66610. 2) secondary trigger (same)
  66611. 3) A (right) X (left), touch, pressed = value
  66612. 4) B / Y
  66613. 5) thumb rest
  66614. */
  66615. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66616. var notifyObject = state; //{ state: state, changes: changes };
  66617. var triggerDirection = this.hand === 'right' ? -1 : 1;
  66618. switch (buttonIdx) {
  66619. case 0:
  66620. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66621. return;
  66622. case 1:// index trigger
  66623. if (this._defaultModel) {
  66624. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  66625. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  66626. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  66627. }
  66628. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66629. return;
  66630. case 2:// secondary trigger
  66631. if (this._defaultModel) {
  66632. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  66633. }
  66634. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  66635. return;
  66636. case 3:
  66637. if (this._defaultModel) {
  66638. if (notifyObject.pressed) {
  66639. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  66640. }
  66641. else {
  66642. (this._defaultModel.getChildren()[1]).position.y = 0;
  66643. }
  66644. }
  66645. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66646. return;
  66647. case 4:
  66648. if (this._defaultModel) {
  66649. if (notifyObject.pressed) {
  66650. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66651. }
  66652. else {
  66653. (this._defaultModel.getChildren()[2]).position.y = 0;
  66654. }
  66655. }
  66656. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66657. return;
  66658. case 5:
  66659. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  66660. return;
  66661. }
  66662. };
  66663. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  66664. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  66665. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  66666. return OculusTouchController;
  66667. }(BABYLON.WebVRController));
  66668. BABYLON.OculusTouchController = OculusTouchController;
  66669. })(BABYLON || (BABYLON = {}));
  66670. //# sourceMappingURL=babylon.oculusTouchController.js.map
  66671. "use strict";
  66672. var BABYLON;
  66673. (function (BABYLON) {
  66674. var ViveController = /** @class */ (function (_super) {
  66675. __extends(ViveController, _super);
  66676. function ViveController(vrGamepad) {
  66677. var _this = _super.call(this, vrGamepad) || this;
  66678. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  66679. _this._invertLeftStickY = true;
  66680. return _this;
  66681. }
  66682. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66683. var _this = this;
  66684. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  66685. /*
  66686. Parent Mesh name: ViveWand
  66687. - body
  66688. - r_gripper
  66689. - l_gripper
  66690. - menu_button
  66691. - system_button
  66692. - trackpad
  66693. - trigger
  66694. - LED
  66695. */
  66696. _this._defaultModel = newMeshes[1];
  66697. _this.attachToMesh(_this._defaultModel);
  66698. if (meshLoaded) {
  66699. meshLoaded(_this._defaultModel);
  66700. }
  66701. });
  66702. };
  66703. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  66704. get: function () {
  66705. return this.onMainButtonStateChangedObservable;
  66706. },
  66707. enumerable: true,
  66708. configurable: true
  66709. });
  66710. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  66711. get: function () {
  66712. return this.onMainButtonStateChangedObservable;
  66713. },
  66714. enumerable: true,
  66715. configurable: true
  66716. });
  66717. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  66718. get: function () {
  66719. return this.onSecondaryButtonStateChangedObservable;
  66720. },
  66721. enumerable: true,
  66722. configurable: true
  66723. });
  66724. /**
  66725. * Vive mapping:
  66726. * 0: touchpad
  66727. * 1: trigger
  66728. * 2: left AND right buttons
  66729. * 3: menu button
  66730. */
  66731. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66732. var notifyObject = state; //{ state: state, changes: changes };
  66733. switch (buttonIdx) {
  66734. case 0:
  66735. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66736. return;
  66737. case 1:// index trigger
  66738. if (this._defaultModel) {
  66739. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  66740. }
  66741. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66742. return;
  66743. case 2:// left AND right button
  66744. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66745. return;
  66746. case 3:
  66747. if (this._defaultModel) {
  66748. if (notifyObject.pressed) {
  66749. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66750. }
  66751. else {
  66752. (this._defaultModel.getChildren()[2]).position.y = 0;
  66753. }
  66754. }
  66755. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66756. return;
  66757. }
  66758. };
  66759. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  66760. ViveController.MODEL_FILENAME = 'wand.babylon';
  66761. return ViveController;
  66762. }(BABYLON.WebVRController));
  66763. BABYLON.ViveController = ViveController;
  66764. })(BABYLON || (BABYLON = {}));
  66765. //# sourceMappingURL=babylon.viveController.js.map
  66766. "use strict";
  66767. var BABYLON;
  66768. (function (BABYLON) {
  66769. var GenericController = /** @class */ (function (_super) {
  66770. __extends(GenericController, _super);
  66771. function GenericController(vrGamepad) {
  66772. return _super.call(this, vrGamepad) || this;
  66773. }
  66774. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66775. var _this = this;
  66776. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  66777. _this._defaultModel = newMeshes[1];
  66778. _this.attachToMesh(_this._defaultModel);
  66779. if (meshLoaded) {
  66780. meshLoaded(_this._defaultModel);
  66781. }
  66782. });
  66783. };
  66784. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66785. console.log("Button id: " + buttonIdx + "state: ");
  66786. console.dir(state);
  66787. };
  66788. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66789. GenericController.MODEL_FILENAME = 'generic.babylon';
  66790. return GenericController;
  66791. }(BABYLON.WebVRController));
  66792. BABYLON.GenericController = GenericController;
  66793. })(BABYLON || (BABYLON = {}));
  66794. //# sourceMappingURL=babylon.genericController.js.map
  66795. "use strict";
  66796. var BABYLON;
  66797. (function (BABYLON) {
  66798. var LoadedMeshInfo = /** @class */ (function () {
  66799. function LoadedMeshInfo() {
  66800. this.buttonMeshes = {};
  66801. this.axisMeshes = {};
  66802. }
  66803. return LoadedMeshInfo;
  66804. }());
  66805. var WindowsMotionController = /** @class */ (function (_super) {
  66806. __extends(WindowsMotionController, _super);
  66807. function WindowsMotionController(vrGamepad) {
  66808. var _this = _super.call(this, vrGamepad) || this;
  66809. _this._mapping = {
  66810. // Semantic button names
  66811. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  66812. // A mapping of the button name to glTF model node name
  66813. // that should be transformed by button value.
  66814. buttonMeshNames: {
  66815. 'trigger': 'SELECT',
  66816. 'menu': 'MENU',
  66817. 'grip': 'GRASP',
  66818. 'thumbstick': 'THUMBSTICK_PRESS',
  66819. 'trackpad': 'TOUCHPAD_PRESS'
  66820. },
  66821. // This mapping is used to translate from the Motion Controller to Babylon semantics
  66822. buttonObservableNames: {
  66823. 'trigger': 'onTriggerStateChangedObservable',
  66824. 'menu': 'onSecondaryButtonStateChangedObservable',
  66825. 'grip': 'onMainButtonStateChangedObservable',
  66826. 'thumbstick': 'onPadStateChangedObservable',
  66827. 'trackpad': 'onTrackpadChangedObservable'
  66828. },
  66829. // A mapping of the axis name to glTF model node name
  66830. // that should be transformed by axis value.
  66831. // This array mirrors the browserGamepad.axes array, such that
  66832. // the mesh corresponding to axis 0 is in this array index 0.
  66833. axisMeshNames: [
  66834. 'THUMBSTICK_X',
  66835. 'THUMBSTICK_Y',
  66836. 'TOUCHPAD_TOUCH_X',
  66837. 'TOUCHPAD_TOUCH_Y'
  66838. ],
  66839. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  66840. };
  66841. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  66842. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  66843. _this.trackpad = { x: 0, y: 0 };
  66844. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  66845. _this._loadedMeshInfo = null;
  66846. return _this;
  66847. }
  66848. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  66849. get: function () {
  66850. return this.onTriggerStateChangedObservable;
  66851. },
  66852. enumerable: true,
  66853. configurable: true
  66854. });
  66855. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  66856. get: function () {
  66857. return this.onSecondaryButtonStateChangedObservable;
  66858. },
  66859. enumerable: true,
  66860. configurable: true
  66861. });
  66862. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  66863. get: function () {
  66864. return this.onMainButtonStateChangedObservable;
  66865. },
  66866. enumerable: true,
  66867. configurable: true
  66868. });
  66869. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  66870. get: function () {
  66871. return this.onPadStateChangedObservable;
  66872. },
  66873. enumerable: true,
  66874. configurable: true
  66875. });
  66876. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  66877. get: function () {
  66878. return this.onTrackpadChangedObservable;
  66879. },
  66880. enumerable: true,
  66881. configurable: true
  66882. });
  66883. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  66884. get: function () {
  66885. return this.onTrackpadValuesChangedObservable;
  66886. },
  66887. enumerable: true,
  66888. configurable: true
  66889. });
  66890. /**
  66891. * Called once per frame by the engine.
  66892. */
  66893. WindowsMotionController.prototype.update = function () {
  66894. _super.prototype.update.call(this);
  66895. if (this.browserGamepad.axes) {
  66896. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  66897. this.trackpad.x = this.browserGamepad["axes"][2];
  66898. this.trackpad.y = this.browserGamepad["axes"][3];
  66899. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  66900. }
  66901. // Only need to animate axes if there is a loaded mesh
  66902. if (this._loadedMeshInfo) {
  66903. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  66904. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  66905. }
  66906. }
  66907. }
  66908. };
  66909. /**
  66910. * Called once for each button that changed state since the last frame
  66911. * @param buttonIdx Which button index changed
  66912. * @param state New state of the button
  66913. * @param changes Which properties on the state changed since last frame
  66914. */
  66915. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66916. var buttonName = this._mapping.buttons[buttonIdx];
  66917. if (!buttonName) {
  66918. return;
  66919. }
  66920. // Only emit events for buttons that we know how to map from index to name
  66921. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  66922. if (observable) {
  66923. observable.notifyObservers(state);
  66924. }
  66925. this.lerpButtonTransform(buttonName, state.value);
  66926. };
  66927. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  66928. // If there is no loaded mesh, there is nothing to transform.
  66929. if (!this._loadedMeshInfo) {
  66930. return;
  66931. }
  66932. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  66933. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66934. return;
  66935. }
  66936. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  66937. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  66938. };
  66939. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  66940. if (!this._loadedMeshInfo) {
  66941. return;
  66942. }
  66943. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  66944. if (!meshInfo) {
  66945. return;
  66946. }
  66947. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66948. return;
  66949. }
  66950. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  66951. var lerpValue = axisValue * 0.5 + 0.5;
  66952. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  66953. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  66954. };
  66955. /**
  66956. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  66957. * @param scene scene in which to add meshes
  66958. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  66959. */
  66960. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  66961. var _this = this;
  66962. if (forceDefault === void 0) { forceDefault = false; }
  66963. var path;
  66964. var filename;
  66965. // Checking if GLB loader is present
  66966. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  66967. // Determine the device specific folder based on the ID suffix
  66968. var device = 'default';
  66969. if (this.id && !forceDefault) {
  66970. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  66971. device = ((match && match[0]) || device);
  66972. }
  66973. // Hand
  66974. if (this.hand === 'left') {
  66975. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  66976. }
  66977. else {
  66978. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  66979. }
  66980. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  66981. }
  66982. else {
  66983. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  66984. path = BABYLON.GenericController.MODEL_BASE_URL;
  66985. filename = BABYLON.GenericController.MODEL_FILENAME;
  66986. }
  66987. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  66988. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  66989. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  66990. if (!_this._loadedMeshInfo) {
  66991. return;
  66992. }
  66993. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  66994. _this.attachToMesh(_this._defaultModel);
  66995. if (meshLoaded) {
  66996. meshLoaded(_this._defaultModel);
  66997. }
  66998. }, null, function (scene, message) {
  66999. BABYLON.Tools.Log(message);
  67000. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  67001. if (!forceDefault) {
  67002. _this.initControllerMesh(scene, meshLoaded, true);
  67003. }
  67004. });
  67005. };
  67006. /**
  67007. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  67008. * can be transformed by button presses and axes values, based on this._mapping.
  67009. *
  67010. * @param scene scene in which the meshes exist
  67011. * @param meshes list of meshes that make up the controller model to process
  67012. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  67013. */
  67014. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  67015. var loadedMeshInfo = null;
  67016. // Create a new mesh to contain the glTF hierarchy
  67017. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  67018. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  67019. var childMesh = null;
  67020. for (var i = 0; i < meshes.length; i++) {
  67021. var mesh = meshes[i];
  67022. if (!mesh.parent) {
  67023. // Exclude controller meshes from picking results
  67024. mesh.isPickable = false;
  67025. // Handle root node, attach to the new parentMesh
  67026. childMesh = mesh;
  67027. break;
  67028. }
  67029. }
  67030. if (childMesh) {
  67031. childMesh.setParent(parentMesh);
  67032. // Create our mesh info. Note that this method will always return non-null.
  67033. loadedMeshInfo = this.createMeshInfo(parentMesh);
  67034. }
  67035. else {
  67036. BABYLON.Tools.Warn('Could not find root node in model file.');
  67037. }
  67038. return loadedMeshInfo;
  67039. };
  67040. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  67041. var loadedMeshInfo = new LoadedMeshInfo();
  67042. var i;
  67043. loadedMeshInfo.rootNode = rootNode;
  67044. // Reset the caches
  67045. loadedMeshInfo.buttonMeshes = {};
  67046. loadedMeshInfo.axisMeshes = {};
  67047. // Button Meshes
  67048. for (i = 0; i < this._mapping.buttons.length; i++) {
  67049. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  67050. if (!buttonMeshName) {
  67051. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  67052. continue;
  67053. }
  67054. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  67055. if (!buttonMesh) {
  67056. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  67057. continue;
  67058. }
  67059. var buttonMeshInfo = {
  67060. index: i,
  67061. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  67062. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  67063. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  67064. };
  67065. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  67066. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  67067. }
  67068. else {
  67069. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  67070. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  67071. '(VALUE: ' + !!buttonMeshInfo.value +
  67072. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  67073. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  67074. ')');
  67075. }
  67076. }
  67077. // Axis Meshes
  67078. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  67079. var axisMeshName = this._mapping.axisMeshNames[i];
  67080. if (!axisMeshName) {
  67081. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  67082. continue;
  67083. }
  67084. var axisMesh = getChildByName(rootNode, axisMeshName);
  67085. if (!axisMesh) {
  67086. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  67087. continue;
  67088. }
  67089. var axisMeshInfo = {
  67090. index: i,
  67091. value: getImmediateChildByName(axisMesh, 'VALUE'),
  67092. min: getImmediateChildByName(axisMesh, 'MIN'),
  67093. max: getImmediateChildByName(axisMesh, 'MAX')
  67094. };
  67095. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  67096. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  67097. }
  67098. else {
  67099. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  67100. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  67101. '(VALUE: ' + !!axisMeshInfo.value +
  67102. ', MIN: ' + !!axisMeshInfo.min +
  67103. ', MAX:' + !!axisMeshInfo.max +
  67104. ')');
  67105. }
  67106. }
  67107. // Pointing Ray
  67108. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  67109. if (!loadedMeshInfo.pointingPoseNode) {
  67110. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  67111. }
  67112. return loadedMeshInfo;
  67113. // Look through all children recursively. This will return null if no mesh exists with the given name.
  67114. function getChildByName(node, name) {
  67115. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  67116. }
  67117. // Look through only immediate children. This will return null if no mesh exists with the given name.
  67118. function getImmediateChildByName(node, name) {
  67119. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  67120. }
  67121. };
  67122. WindowsMotionController.prototype.getForwardRay = function (length) {
  67123. if (length === void 0) { length = 100; }
  67124. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  67125. return _super.prototype.getForwardRay.call(this, length);
  67126. }
  67127. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  67128. var origin = m.getTranslation();
  67129. var forward = new BABYLON.Vector3(0, 0, -1);
  67130. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  67131. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  67132. return new BABYLON.Ray(origin, direction, length);
  67133. };
  67134. WindowsMotionController.prototype.dispose = function () {
  67135. _super.prototype.dispose.call(this);
  67136. this.onTrackpadChangedObservable.clear();
  67137. };
  67138. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  67139. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  67140. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  67141. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  67142. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  67143. return WindowsMotionController;
  67144. }(BABYLON.WebVRController));
  67145. BABYLON.WindowsMotionController = WindowsMotionController;
  67146. })(BABYLON || (BABYLON = {}));
  67147. //# sourceMappingURL=babylon.windowsMotionController.js.map
  67148. "use strict";
  67149. var BABYLON;
  67150. (function (BABYLON) {
  67151. var GearVRController = /** @class */ (function (_super) {
  67152. __extends(GearVRController, _super);
  67153. function GearVRController(vrGamepad) {
  67154. var _this = _super.call(this, vrGamepad) || this;
  67155. _this._buttonIndexToObservableNameMap = [
  67156. 'onTrackpadChangedObservable',
  67157. 'onTriggerStateChangedObservable' // Trigger
  67158. ];
  67159. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  67160. return _this;
  67161. }
  67162. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67163. var _this = this;
  67164. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  67165. _this._defaultModel = newMeshes[1];
  67166. _this.attachToMesh(_this._defaultModel);
  67167. if (meshLoaded) {
  67168. meshLoaded(_this._defaultModel);
  67169. }
  67170. });
  67171. };
  67172. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67173. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  67174. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  67175. // Only emit events for buttons that we know how to map from index to observable
  67176. var observable = this[observableName];
  67177. if (observable) {
  67178. observable.notifyObservers(state);
  67179. }
  67180. }
  67181. };
  67182. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67183. GearVRController.MODEL_FILENAME = 'generic.babylon';
  67184. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  67185. return GearVRController;
  67186. }(BABYLON.WebVRController));
  67187. BABYLON.GearVRController = GearVRController;
  67188. })(BABYLON || (BABYLON = {}));
  67189. //# sourceMappingURL=babylon.gearVRController.js.map
  67190. "use strict";
  67191. var BABYLON;
  67192. (function (BABYLON) {
  67193. /**
  67194. * Google Daydream controller
  67195. */
  67196. var DaydreamController = /** @class */ (function (_super) {
  67197. __extends(DaydreamController, _super);
  67198. function DaydreamController(vrGamepad) {
  67199. var _this = _super.call(this, vrGamepad) || this;
  67200. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  67201. return _this;
  67202. }
  67203. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67204. var _this = this;
  67205. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  67206. _this._defaultModel = newMeshes[1];
  67207. _this.attachToMesh(_this._defaultModel);
  67208. if (meshLoaded) {
  67209. meshLoaded(_this._defaultModel);
  67210. }
  67211. });
  67212. };
  67213. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67214. // Daydream controller only has 1 GamepadButton (on the trackpad).
  67215. if (buttonIdx === 0) {
  67216. var observable = this.onTriggerStateChangedObservable;
  67217. if (observable) {
  67218. observable.notifyObservers(state);
  67219. }
  67220. }
  67221. else {
  67222. // If the app or home buttons are ever made available
  67223. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  67224. }
  67225. };
  67226. /**
  67227. * Base Url for the controller model.
  67228. */
  67229. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67230. /**
  67231. * File name for the controller model.
  67232. */
  67233. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  67234. /**
  67235. * Gamepad Id prefix used to identify Daydream Controller.
  67236. */
  67237. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  67238. return DaydreamController;
  67239. }(BABYLON.WebVRController));
  67240. BABYLON.DaydreamController = DaydreamController;
  67241. })(BABYLON || (BABYLON = {}));
  67242. //# sourceMappingURL=babylon.daydreamController.js.map
  67243. "use strict";
  67244. var BABYLON;
  67245. (function (BABYLON) {
  67246. var FollowCamera = /** @class */ (function (_super) {
  67247. __extends(FollowCamera, _super);
  67248. function FollowCamera(name, position, scene, lockedTarget) {
  67249. if (lockedTarget === void 0) { lockedTarget = null; }
  67250. var _this = _super.call(this, name, position, scene) || this;
  67251. _this.radius = 12;
  67252. _this.rotationOffset = 0;
  67253. _this.heightOffset = 4;
  67254. _this.cameraAcceleration = 0.05;
  67255. _this.maxCameraSpeed = 20;
  67256. _this.lockedTarget = lockedTarget;
  67257. return _this;
  67258. }
  67259. FollowCamera.prototype.getRadians = function (degrees) {
  67260. return degrees * Math.PI / 180;
  67261. };
  67262. FollowCamera.prototype.follow = function (cameraTarget) {
  67263. if (!cameraTarget)
  67264. return;
  67265. var yRotation;
  67266. if (cameraTarget.rotationQuaternion) {
  67267. var rotMatrix = new BABYLON.Matrix();
  67268. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  67269. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  67270. }
  67271. else {
  67272. yRotation = cameraTarget.rotation.y;
  67273. }
  67274. var radians = this.getRadians(this.rotationOffset) + yRotation;
  67275. var targetPosition = cameraTarget.getAbsolutePosition();
  67276. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  67277. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  67278. var dx = targetX - this.position.x;
  67279. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  67280. var dz = (targetZ) - this.position.z;
  67281. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  67282. var vy = dy * this.cameraAcceleration;
  67283. var vz = dz * this.cameraAcceleration * 2;
  67284. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  67285. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67286. }
  67287. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  67288. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67289. }
  67290. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  67291. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67292. }
  67293. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  67294. this.setTarget(targetPosition);
  67295. };
  67296. FollowCamera.prototype._checkInputs = function () {
  67297. _super.prototype._checkInputs.call(this);
  67298. if (this.lockedTarget) {
  67299. this.follow(this.lockedTarget);
  67300. }
  67301. };
  67302. FollowCamera.prototype.getClassName = function () {
  67303. return "FollowCamera";
  67304. };
  67305. __decorate([
  67306. BABYLON.serialize()
  67307. ], FollowCamera.prototype, "radius", void 0);
  67308. __decorate([
  67309. BABYLON.serialize()
  67310. ], FollowCamera.prototype, "rotationOffset", void 0);
  67311. __decorate([
  67312. BABYLON.serialize()
  67313. ], FollowCamera.prototype, "heightOffset", void 0);
  67314. __decorate([
  67315. BABYLON.serialize()
  67316. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  67317. __decorate([
  67318. BABYLON.serialize()
  67319. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  67320. __decorate([
  67321. BABYLON.serializeAsMeshReference("lockedTargetId")
  67322. ], FollowCamera.prototype, "lockedTarget", void 0);
  67323. return FollowCamera;
  67324. }(BABYLON.TargetCamera));
  67325. BABYLON.FollowCamera = FollowCamera;
  67326. var ArcFollowCamera = /** @class */ (function (_super) {
  67327. __extends(ArcFollowCamera, _super);
  67328. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  67329. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  67330. _this.alpha = alpha;
  67331. _this.beta = beta;
  67332. _this.radius = radius;
  67333. _this.target = target;
  67334. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  67335. _this.follow();
  67336. return _this;
  67337. }
  67338. ArcFollowCamera.prototype.follow = function () {
  67339. if (!this.target) {
  67340. return;
  67341. }
  67342. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  67343. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  67344. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  67345. var targetPosition = this.target.getAbsolutePosition();
  67346. this.position = targetPosition.add(this._cartesianCoordinates);
  67347. this.setTarget(targetPosition);
  67348. };
  67349. ArcFollowCamera.prototype._checkInputs = function () {
  67350. _super.prototype._checkInputs.call(this);
  67351. this.follow();
  67352. };
  67353. ArcFollowCamera.prototype.getClassName = function () {
  67354. return "ArcFollowCamera";
  67355. };
  67356. return ArcFollowCamera;
  67357. }(BABYLON.TargetCamera));
  67358. BABYLON.ArcFollowCamera = ArcFollowCamera;
  67359. })(BABYLON || (BABYLON = {}));
  67360. //# sourceMappingURL=babylon.followCamera.js.map
  67361. "use strict";
  67362. var BABYLON;
  67363. (function (BABYLON) {
  67364. // We're mainly based on the logic defined into the FreeCamera code
  67365. var UniversalCamera = /** @class */ (function (_super) {
  67366. __extends(UniversalCamera, _super);
  67367. //-- end properties for backward compatibility for inputs
  67368. function UniversalCamera(name, position, scene) {
  67369. var _this = _super.call(this, name, position, scene) || this;
  67370. _this.inputs.addGamepad();
  67371. return _this;
  67372. }
  67373. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  67374. //-- Begin properties for backward compatibility for inputs
  67375. get: function () {
  67376. var gamepad = this.inputs.attached["gamepad"];
  67377. if (gamepad)
  67378. return gamepad.gamepadAngularSensibility;
  67379. return 0;
  67380. },
  67381. set: function (value) {
  67382. var gamepad = this.inputs.attached["gamepad"];
  67383. if (gamepad)
  67384. gamepad.gamepadAngularSensibility = value;
  67385. },
  67386. enumerable: true,
  67387. configurable: true
  67388. });
  67389. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  67390. get: function () {
  67391. var gamepad = this.inputs.attached["gamepad"];
  67392. if (gamepad)
  67393. return gamepad.gamepadMoveSensibility;
  67394. return 0;
  67395. },
  67396. set: function (value) {
  67397. var gamepad = this.inputs.attached["gamepad"];
  67398. if (gamepad)
  67399. gamepad.gamepadMoveSensibility = value;
  67400. },
  67401. enumerable: true,
  67402. configurable: true
  67403. });
  67404. UniversalCamera.prototype.getClassName = function () {
  67405. return "UniversalCamera";
  67406. };
  67407. return UniversalCamera;
  67408. }(BABYLON.TouchCamera));
  67409. BABYLON.UniversalCamera = UniversalCamera;
  67410. })(BABYLON || (BABYLON = {}));
  67411. //# sourceMappingURL=babylon.universalCamera.js.map
  67412. "use strict";
  67413. var BABYLON;
  67414. (function (BABYLON) {
  67415. // We're mainly based on the logic defined into the FreeCamera code
  67416. var GamepadCamera = /** @class */ (function (_super) {
  67417. __extends(GamepadCamera, _super);
  67418. //-- end properties for backward compatibility for inputs
  67419. function GamepadCamera(name, position, scene) {
  67420. return _super.call(this, name, position, scene) || this;
  67421. }
  67422. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  67423. //-- Begin properties for backward compatibility for inputs
  67424. get: function () {
  67425. var gamepad = this.inputs.attached["gamepad"];
  67426. if (gamepad)
  67427. return gamepad.gamepadAngularSensibility;
  67428. return 0;
  67429. },
  67430. set: function (value) {
  67431. var gamepad = this.inputs.attached["gamepad"];
  67432. if (gamepad)
  67433. gamepad.gamepadAngularSensibility = value;
  67434. },
  67435. enumerable: true,
  67436. configurable: true
  67437. });
  67438. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  67439. get: function () {
  67440. var gamepad = this.inputs.attached["gamepad"];
  67441. if (gamepad)
  67442. return gamepad.gamepadMoveSensibility;
  67443. return 0;
  67444. },
  67445. set: function (value) {
  67446. var gamepad = this.inputs.attached["gamepad"];
  67447. if (gamepad)
  67448. gamepad.gamepadMoveSensibility = value;
  67449. },
  67450. enumerable: true,
  67451. configurable: true
  67452. });
  67453. GamepadCamera.prototype.getClassName = function () {
  67454. return "GamepadCamera";
  67455. };
  67456. return GamepadCamera;
  67457. }(BABYLON.UniversalCamera));
  67458. BABYLON.GamepadCamera = GamepadCamera;
  67459. })(BABYLON || (BABYLON = {}));
  67460. //# sourceMappingURL=babylon.gamepadCamera.js.map
  67461. "use strict";
  67462. var BABYLON;
  67463. (function (BABYLON) {
  67464. var PostProcessRenderPipelineManager = /** @class */ (function () {
  67465. function PostProcessRenderPipelineManager() {
  67466. this._renderPipelines = {};
  67467. }
  67468. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  67469. this._renderPipelines[renderPipeline._name] = renderPipeline;
  67470. };
  67471. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  67472. if (unique === void 0) { unique = false; }
  67473. var renderPipeline = this._renderPipelines[renderPipelineName];
  67474. if (!renderPipeline) {
  67475. return;
  67476. }
  67477. renderPipeline._attachCameras(cameras, unique);
  67478. };
  67479. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  67480. var renderPipeline = this._renderPipelines[renderPipelineName];
  67481. if (!renderPipeline) {
  67482. return;
  67483. }
  67484. renderPipeline._detachCameras(cameras);
  67485. };
  67486. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67487. var renderPipeline = this._renderPipelines[renderPipelineName];
  67488. if (!renderPipeline) {
  67489. return;
  67490. }
  67491. renderPipeline._enableEffect(renderEffectName, cameras);
  67492. };
  67493. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67494. var renderPipeline = this._renderPipelines[renderPipelineName];
  67495. if (!renderPipeline) {
  67496. return;
  67497. }
  67498. renderPipeline._disableEffect(renderEffectName, cameras);
  67499. };
  67500. PostProcessRenderPipelineManager.prototype.update = function () {
  67501. for (var renderPipelineName in this._renderPipelines) {
  67502. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67503. var pipeline = this._renderPipelines[renderPipelineName];
  67504. if (!pipeline.isSupported) {
  67505. pipeline.dispose();
  67506. delete this._renderPipelines[renderPipelineName];
  67507. }
  67508. else {
  67509. pipeline._update();
  67510. }
  67511. }
  67512. }
  67513. };
  67514. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  67515. for (var renderPipelineName in this._renderPipelines) {
  67516. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67517. var pipeline = this._renderPipelines[renderPipelineName];
  67518. pipeline._rebuild();
  67519. }
  67520. }
  67521. };
  67522. PostProcessRenderPipelineManager.prototype.dispose = function () {
  67523. for (var renderPipelineName in this._renderPipelines) {
  67524. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67525. var pipeline = this._renderPipelines[renderPipelineName];
  67526. pipeline.dispose();
  67527. }
  67528. }
  67529. };
  67530. return PostProcessRenderPipelineManager;
  67531. }());
  67532. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  67533. })(BABYLON || (BABYLON = {}));
  67534. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  67535. "use strict";
  67536. var BABYLON;
  67537. (function (BABYLON) {
  67538. /**
  67539. * This represents a set of one or more post processes in Babylon.
  67540. * A post process can be used to apply a shader to a texture after it is rendered.
  67541. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  67542. */
  67543. var PostProcessRenderEffect = /** @class */ (function () {
  67544. /**
  67545. * Instantiates a post process render effect.
  67546. * A post process can be used to apply a shader to a texture after it is rendered.
  67547. * @param engine The engine the effect is tied to
  67548. * @param name The name of the effect
  67549. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  67550. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  67551. */
  67552. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  67553. this._name = name;
  67554. this._singleInstance = singleInstance || true;
  67555. this._getPostProcesses = getPostProcesses;
  67556. this._cameras = {};
  67557. this._indicesForCamera = {};
  67558. this._postProcesses = {};
  67559. }
  67560. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  67561. /**
  67562. * Checks if all the post processes in the effect are supported.
  67563. */
  67564. get: function () {
  67565. for (var index in this._postProcesses) {
  67566. for (var ppIndex in this._postProcesses[index]) {
  67567. if (!this._postProcesses[index][ppIndex].isSupported) {
  67568. return false;
  67569. }
  67570. }
  67571. }
  67572. return true;
  67573. },
  67574. enumerable: true,
  67575. configurable: true
  67576. });
  67577. /**
  67578. * Updates the current state of the effect
  67579. */
  67580. PostProcessRenderEffect.prototype._update = function () {
  67581. };
  67582. /**
  67583. * Attaches the effect on cameras
  67584. * @param cameras The camera to attach to.
  67585. */
  67586. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  67587. var _this = this;
  67588. var cameraKey;
  67589. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67590. if (!cams) {
  67591. return;
  67592. }
  67593. for (var i = 0; i < cams.length; i++) {
  67594. var camera = cams[i];
  67595. var cameraName = camera.name;
  67596. if (this._singleInstance) {
  67597. cameraKey = 0;
  67598. }
  67599. else {
  67600. cameraKey = cameraName;
  67601. }
  67602. if (!this._postProcesses[cameraKey]) {
  67603. var postProcess = this._getPostProcesses();
  67604. if (postProcess) {
  67605. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  67606. }
  67607. }
  67608. if (!this._indicesForCamera[cameraName]) {
  67609. this._indicesForCamera[cameraName] = [];
  67610. }
  67611. this._postProcesses[cameraKey].forEach(function (postProcess) {
  67612. var index = camera.attachPostProcess(postProcess);
  67613. _this._indicesForCamera[cameraName].push(index);
  67614. });
  67615. if (!this._cameras[cameraName]) {
  67616. this._cameras[cameraName] = camera;
  67617. }
  67618. }
  67619. };
  67620. /**
  67621. * Detatches the effect on cameras
  67622. * @param cameras The camera to detatch from.
  67623. */
  67624. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  67625. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67626. if (!cams) {
  67627. return;
  67628. }
  67629. for (var i = 0; i < cams.length; i++) {
  67630. var camera = cams[i];
  67631. var cameraName = camera.name;
  67632. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67633. camera.detachPostProcess(postProcess);
  67634. });
  67635. if (this._cameras[cameraName]) {
  67636. //this._indicesForCamera.splice(index, 1);
  67637. this._cameras[cameraName] = null;
  67638. }
  67639. }
  67640. };
  67641. /**
  67642. * Enables the effect on given cameras
  67643. * @param cameras The camera to enable.
  67644. */
  67645. PostProcessRenderEffect.prototype._enable = function (cameras) {
  67646. var _this = this;
  67647. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67648. if (!cams) {
  67649. return;
  67650. }
  67651. for (var i = 0; i < cams.length; i++) {
  67652. var camera = cams[i];
  67653. var cameraName = camera.name;
  67654. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  67655. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  67656. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67657. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  67658. });
  67659. }
  67660. }
  67661. }
  67662. };
  67663. /**
  67664. * Disables the effect on the given cameras
  67665. * @param cameras The camera to disable.
  67666. */
  67667. PostProcessRenderEffect.prototype._disable = function (cameras) {
  67668. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67669. if (!cams) {
  67670. return;
  67671. }
  67672. for (var i = 0; i < cams.length; i++) {
  67673. var camera = cams[i];
  67674. var cameraName = camera.name;
  67675. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67676. camera.detachPostProcess(postProcess);
  67677. });
  67678. }
  67679. };
  67680. /**
  67681. * Gets a list of the post processes contained in the effect.
  67682. * @param camera The camera to get the post processes on.
  67683. * @returns The list of the post processes in the effect.
  67684. */
  67685. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  67686. if (this._singleInstance) {
  67687. return this._postProcesses[0];
  67688. }
  67689. else {
  67690. if (!camera) {
  67691. return null;
  67692. }
  67693. return this._postProcesses[camera.name];
  67694. }
  67695. };
  67696. return PostProcessRenderEffect;
  67697. }());
  67698. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  67699. })(BABYLON || (BABYLON = {}));
  67700. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  67701. "use strict";
  67702. var BABYLON;
  67703. (function (BABYLON) {
  67704. var PostProcessRenderPipeline = /** @class */ (function () {
  67705. function PostProcessRenderPipeline(engine, name) {
  67706. this.engine = engine;
  67707. this._name = name;
  67708. this._renderEffects = {};
  67709. this._renderEffectsForIsolatedPass = new Array();
  67710. this._cameras = [];
  67711. }
  67712. PostProcessRenderPipeline.prototype.getClassName = function () {
  67713. return "PostProcessRenderPipeline";
  67714. };
  67715. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  67716. get: function () {
  67717. for (var renderEffectName in this._renderEffects) {
  67718. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67719. if (!this._renderEffects[renderEffectName].isSupported) {
  67720. return false;
  67721. }
  67722. }
  67723. }
  67724. return true;
  67725. },
  67726. enumerable: true,
  67727. configurable: true
  67728. });
  67729. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  67730. this._renderEffects[renderEffect._name] = renderEffect;
  67731. };
  67732. // private
  67733. PostProcessRenderPipeline.prototype._rebuild = function () {
  67734. };
  67735. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  67736. var renderEffects = this._renderEffects[renderEffectName];
  67737. if (!renderEffects) {
  67738. return;
  67739. }
  67740. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67741. };
  67742. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  67743. var renderEffects = this._renderEffects[renderEffectName];
  67744. if (!renderEffects) {
  67745. return;
  67746. }
  67747. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67748. };
  67749. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  67750. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67751. if (!cams) {
  67752. return;
  67753. }
  67754. var indicesToDelete = [];
  67755. var i;
  67756. for (i = 0; i < cams.length; i++) {
  67757. var camera = cams[i];
  67758. var cameraName = camera.name;
  67759. if (this._cameras.indexOf(camera) === -1) {
  67760. this._cameras[cameraName] = camera;
  67761. }
  67762. else if (unique) {
  67763. indicesToDelete.push(i);
  67764. }
  67765. }
  67766. for (i = 0; i < indicesToDelete.length; i++) {
  67767. cameras.splice(indicesToDelete[i], 1);
  67768. }
  67769. for (var renderEffectName in this._renderEffects) {
  67770. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67771. this._renderEffects[renderEffectName]._attachCameras(cams);
  67772. }
  67773. }
  67774. };
  67775. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  67776. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67777. if (!cams) {
  67778. return;
  67779. }
  67780. for (var renderEffectName in this._renderEffects) {
  67781. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67782. this._renderEffects[renderEffectName]._detachCameras(cams);
  67783. }
  67784. }
  67785. for (var i = 0; i < cams.length; i++) {
  67786. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  67787. }
  67788. };
  67789. PostProcessRenderPipeline.prototype._update = function () {
  67790. for (var renderEffectName in this._renderEffects) {
  67791. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67792. this._renderEffects[renderEffectName]._update();
  67793. }
  67794. }
  67795. for (var i = 0; i < this._cameras.length; i++) {
  67796. var cameraName = this._cameras[i].name;
  67797. if (this._renderEffectsForIsolatedPass[cameraName]) {
  67798. this._renderEffectsForIsolatedPass[cameraName]._update();
  67799. }
  67800. }
  67801. };
  67802. PostProcessRenderPipeline.prototype._reset = function () {
  67803. this._renderEffects = {};
  67804. this._renderEffectsForIsolatedPass = new Array();
  67805. };
  67806. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  67807. // 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)
  67808. var effectKeys = Object.keys(this._renderEffects);
  67809. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  67810. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  67811. if (postProcesses) {
  67812. postProcesses[0].samples = 4;
  67813. return true;
  67814. }
  67815. }
  67816. return false;
  67817. };
  67818. PostProcessRenderPipeline.prototype.dispose = function () {
  67819. // Must be implemented by children
  67820. };
  67821. __decorate([
  67822. BABYLON.serialize()
  67823. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  67824. return PostProcessRenderPipeline;
  67825. }());
  67826. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  67827. })(BABYLON || (BABYLON = {}));
  67828. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  67829. "use strict";
  67830. var BABYLON;
  67831. (function (BABYLON) {
  67832. /**
  67833. * This represents a depth renderer in Babylon.
  67834. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  67835. */
  67836. var DepthRenderer = /** @class */ (function () {
  67837. /**
  67838. * Instantiates a depth renderer
  67839. * @param scene The scene the renderer belongs to
  67840. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  67841. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  67842. */
  67843. function DepthRenderer(scene, type, camera) {
  67844. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  67845. if (camera === void 0) { camera = null; }
  67846. var _this = this;
  67847. this._scene = scene;
  67848. this._camera = camera;
  67849. var engine = scene.getEngine();
  67850. // Render target
  67851. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  67852. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67853. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67854. this._depthMap.refreshRate = 1;
  67855. this._depthMap.renderParticles = false;
  67856. this._depthMap.renderList = null;
  67857. // Camera to get depth map from to support multiple concurrent cameras
  67858. this._depthMap.activeCamera = this._camera;
  67859. this._depthMap.ignoreCameraViewport = true;
  67860. this._depthMap.useCameraPostProcesses = false;
  67861. // set default depth value to 1.0 (far away)
  67862. this._depthMap.onClearObservable.add(function (engine) {
  67863. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  67864. });
  67865. // Custom render function
  67866. var renderSubMesh = function (subMesh) {
  67867. var mesh = subMesh.getRenderingMesh();
  67868. var scene = _this._scene;
  67869. var engine = scene.getEngine();
  67870. var material = subMesh.getMaterial();
  67871. if (!material) {
  67872. return;
  67873. }
  67874. // Culling and reverse (right handed system)
  67875. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67876. // Managing instances
  67877. var batch = mesh._getInstancesRenderList(subMesh._id);
  67878. if (batch.mustReturn) {
  67879. return;
  67880. }
  67881. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67882. var camera = _this._camera || scene.activeCamera;
  67883. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  67884. engine.enableEffect(_this._effect);
  67885. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67886. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67887. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  67888. // Alpha test
  67889. if (material && material.needAlphaTesting()) {
  67890. var alphaTexture = material.getAlphaTestTexture();
  67891. if (alphaTexture) {
  67892. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67893. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67894. }
  67895. }
  67896. // Bones
  67897. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67898. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67899. }
  67900. // Draw
  67901. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67902. }
  67903. };
  67904. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67905. var index;
  67906. if (depthOnlySubMeshes.length) {
  67907. engine.setColorWrite(false);
  67908. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67909. renderSubMesh(depthOnlySubMeshes.data[index]);
  67910. }
  67911. engine.setColorWrite(true);
  67912. }
  67913. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67914. renderSubMesh(opaqueSubMeshes.data[index]);
  67915. }
  67916. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67917. renderSubMesh(alphaTestSubMeshes.data[index]);
  67918. }
  67919. };
  67920. }
  67921. /**
  67922. * Creates the depth rendering effect and checks if the effect is ready.
  67923. * @param subMesh The submesh to be used to render the depth map of
  67924. * @param useInstances If multiple world instances should be used
  67925. * @returns if the depth renderer is ready to render the depth map
  67926. */
  67927. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  67928. var material = subMesh.getMaterial();
  67929. if (material.disableDepthWrite) {
  67930. return false;
  67931. }
  67932. var defines = [];
  67933. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67934. var mesh = subMesh.getMesh();
  67935. // Alpha test
  67936. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  67937. defines.push("#define ALPHATEST");
  67938. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67939. attribs.push(BABYLON.VertexBuffer.UVKind);
  67940. defines.push("#define UV1");
  67941. }
  67942. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67943. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67944. defines.push("#define UV2");
  67945. }
  67946. }
  67947. // Bones
  67948. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67949. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67950. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67951. if (mesh.numBoneInfluencers > 4) {
  67952. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67953. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67954. }
  67955. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67956. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  67957. }
  67958. else {
  67959. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67960. }
  67961. // Instances
  67962. if (useInstances) {
  67963. defines.push("#define INSTANCES");
  67964. attribs.push("world0");
  67965. attribs.push("world1");
  67966. attribs.push("world2");
  67967. attribs.push("world3");
  67968. }
  67969. // Get correct effect
  67970. var join = defines.join("\n");
  67971. if (this._cachedDefines !== join) {
  67972. this._cachedDefines = join;
  67973. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  67974. }
  67975. return this._effect.isReady();
  67976. };
  67977. /**
  67978. * Gets the texture which the depth map will be written to.
  67979. * @returns The depth map texture
  67980. */
  67981. DepthRenderer.prototype.getDepthMap = function () {
  67982. return this._depthMap;
  67983. };
  67984. /**
  67985. * Disposes of the depth renderer.
  67986. */
  67987. DepthRenderer.prototype.dispose = function () {
  67988. this._depthMap.dispose();
  67989. };
  67990. return DepthRenderer;
  67991. }());
  67992. BABYLON.DepthRenderer = DepthRenderer;
  67993. })(BABYLON || (BABYLON = {}));
  67994. //# sourceMappingURL=babylon.depthRenderer.js.map
  67995. "use strict";
  67996. var BABYLON;
  67997. (function (BABYLON) {
  67998. var SSAORenderingPipeline = /** @class */ (function (_super) {
  67999. __extends(SSAORenderingPipeline, _super);
  68000. /**
  68001. * @constructor
  68002. * @param {string} name - The rendering pipeline name
  68003. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68004. * @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 }
  68005. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68006. */
  68007. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  68008. var _this = _super.call(this, scene.getEngine(), name) || this;
  68009. // Members
  68010. /**
  68011. * The PassPostProcess id in the pipeline that contains the original scene color
  68012. * @type {string}
  68013. */
  68014. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68015. /**
  68016. * The SSAO PostProcess id in the pipeline
  68017. * @type {string}
  68018. */
  68019. _this.SSAORenderEffect = "SSAORenderEffect";
  68020. /**
  68021. * The horizontal blur PostProcess id in the pipeline
  68022. * @type {string}
  68023. */
  68024. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68025. /**
  68026. * The vertical blur PostProcess id in the pipeline
  68027. * @type {string}
  68028. */
  68029. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68030. /**
  68031. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68032. * @type {string}
  68033. */
  68034. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68035. /**
  68036. * The output strength of the SSAO post-process. Default value is 1.0.
  68037. * @type {number}
  68038. */
  68039. _this.totalStrength = 1.0;
  68040. /**
  68041. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  68042. * @type {number}
  68043. */
  68044. _this.radius = 0.0001;
  68045. /**
  68046. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  68047. * Must not be equal to fallOff and superior to fallOff.
  68048. * Default value is 0.975
  68049. * @type {number}
  68050. */
  68051. _this.area = 0.0075;
  68052. /**
  68053. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  68054. * Must not be equal to area and inferior to area.
  68055. * Default value is 0.0
  68056. * @type {number}
  68057. */
  68058. _this.fallOff = 0.000001;
  68059. /**
  68060. * The base color of the SSAO post-process
  68061. * The final result is "base + ssao" between [0, 1]
  68062. * @type {number}
  68063. */
  68064. _this.base = 0.5;
  68065. _this._firstUpdate = true;
  68066. _this._scene = scene;
  68067. // Set up assets
  68068. _this._createRandomTexture();
  68069. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68070. var ssaoRatio = ratio.ssaoRatio || ratio;
  68071. var combineRatio = ratio.combineRatio || ratio;
  68072. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68073. _this._createSSAOPostProcess(ssaoRatio);
  68074. _this._createBlurPostProcess(ssaoRatio);
  68075. _this._createSSAOCombinePostProcess(combineRatio);
  68076. // Set up pipeline
  68077. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68078. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68079. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68080. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68081. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68082. // Finish
  68083. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68084. if (cameras)
  68085. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68086. return _this;
  68087. }
  68088. // Public Methods
  68089. /**
  68090. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68091. */
  68092. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68093. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68094. for (var i = 0; i < this._scene.cameras.length; i++) {
  68095. var camera = this._scene.cameras[i];
  68096. this._originalColorPostProcess.dispose(camera);
  68097. this._ssaoPostProcess.dispose(camera);
  68098. this._blurHPostProcess.dispose(camera);
  68099. this._blurVPostProcess.dispose(camera);
  68100. this._ssaoCombinePostProcess.dispose(camera);
  68101. }
  68102. this._randomTexture.dispose();
  68103. if (disableDepthRender)
  68104. this._scene.disableDepthRenderer();
  68105. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68106. _super.prototype.dispose.call(this);
  68107. };
  68108. // Private Methods
  68109. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  68110. var _this = this;
  68111. var size = 16;
  68112. 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);
  68113. 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);
  68114. this._blurHPostProcess.onActivateObservable.add(function () {
  68115. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  68116. _this._blurHPostProcess.kernel = size * dw;
  68117. });
  68118. this._blurVPostProcess.onActivateObservable.add(function () {
  68119. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  68120. _this._blurVPostProcess.kernel = size * dw;
  68121. });
  68122. };
  68123. SSAORenderingPipeline.prototype._rebuild = function () {
  68124. this._firstUpdate = true;
  68125. _super.prototype._rebuild.call(this);
  68126. };
  68127. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68128. var _this = this;
  68129. var numSamples = 16;
  68130. var sampleSphere = [
  68131. 0.5381, 0.1856, -0.4319,
  68132. 0.1379, 0.2486, 0.4430,
  68133. 0.3371, 0.5679, -0.0057,
  68134. -0.6999, -0.0451, -0.0019,
  68135. 0.0689, -0.1598, -0.8547,
  68136. 0.0560, 0.0069, -0.1843,
  68137. -0.0146, 0.1402, 0.0762,
  68138. 0.0100, -0.1924, -0.0344,
  68139. -0.3577, -0.5301, -0.4358,
  68140. -0.3169, 0.1063, 0.0158,
  68141. 0.0103, -0.5869, 0.0046,
  68142. -0.0897, -0.4940, 0.3287,
  68143. 0.7119, -0.0154, -0.0918,
  68144. -0.0533, 0.0596, -0.5411,
  68145. 0.0352, -0.0631, 0.5460,
  68146. -0.4776, 0.2847, -0.0271
  68147. ];
  68148. var samplesFactor = 1.0 / numSamples;
  68149. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  68150. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68151. "area", "fallOff", "base", "range", "viewport"
  68152. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68153. this._ssaoPostProcess.onApply = function (effect) {
  68154. if (_this._firstUpdate) {
  68155. effect.setArray3("sampleSphere", sampleSphere);
  68156. effect.setFloat("samplesFactor", samplesFactor);
  68157. effect.setFloat("randTextureTiles", 4.0);
  68158. }
  68159. effect.setFloat("totalStrength", _this.totalStrength);
  68160. effect.setFloat("radius", _this.radius);
  68161. effect.setFloat("area", _this.area);
  68162. effect.setFloat("fallOff", _this.fallOff);
  68163. effect.setFloat("base", _this.base);
  68164. effect.setTexture("textureSampler", _this._depthTexture);
  68165. effect.setTexture("randomSampler", _this._randomTexture);
  68166. };
  68167. };
  68168. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68169. var _this = this;
  68170. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68171. this._ssaoCombinePostProcess.onApply = function (effect) {
  68172. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68173. };
  68174. };
  68175. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  68176. var size = 512;
  68177. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68178. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68179. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68180. var context = this._randomTexture.getContext();
  68181. var rand = function (min, max) {
  68182. return Math.random() * (max - min) + min;
  68183. };
  68184. var randVector = BABYLON.Vector3.Zero();
  68185. for (var x = 0; x < size; x++) {
  68186. for (var y = 0; y < size; y++) {
  68187. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  68188. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  68189. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  68190. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68191. context.fillRect(x, y, 1, 1);
  68192. }
  68193. }
  68194. this._randomTexture.update(false);
  68195. };
  68196. __decorate([
  68197. BABYLON.serialize()
  68198. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  68199. __decorate([
  68200. BABYLON.serialize()
  68201. ], SSAORenderingPipeline.prototype, "radius", void 0);
  68202. __decorate([
  68203. BABYLON.serialize()
  68204. ], SSAORenderingPipeline.prototype, "area", void 0);
  68205. __decorate([
  68206. BABYLON.serialize()
  68207. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  68208. __decorate([
  68209. BABYLON.serialize()
  68210. ], SSAORenderingPipeline.prototype, "base", void 0);
  68211. return SSAORenderingPipeline;
  68212. }(BABYLON.PostProcessRenderPipeline));
  68213. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  68214. })(BABYLON || (BABYLON = {}));
  68215. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  68216. "use strict";
  68217. var BABYLON;
  68218. (function (BABYLON) {
  68219. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  68220. __extends(SSAO2RenderingPipeline, _super);
  68221. /**
  68222. * @constructor
  68223. * @param {string} name - The rendering pipeline name
  68224. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68225. * @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 }
  68226. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68227. */
  68228. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  68229. var _this = _super.call(this, scene.getEngine(), name) || this;
  68230. // Members
  68231. /**
  68232. * The PassPostProcess id in the pipeline that contains the original scene color
  68233. * @type {string}
  68234. */
  68235. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68236. /**
  68237. * The SSAO PostProcess id in the pipeline
  68238. * @type {string}
  68239. */
  68240. _this.SSAORenderEffect = "SSAORenderEffect";
  68241. /**
  68242. * The horizontal blur PostProcess id in the pipeline
  68243. * @type {string}
  68244. */
  68245. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68246. /**
  68247. * The vertical blur PostProcess id in the pipeline
  68248. * @type {string}
  68249. */
  68250. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68251. /**
  68252. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68253. * @type {string}
  68254. */
  68255. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68256. /**
  68257. * The output strength of the SSAO post-process. Default value is 1.0.
  68258. * @type {number}
  68259. */
  68260. _this.totalStrength = 1.0;
  68261. /**
  68262. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  68263. * @type {number}
  68264. */
  68265. _this.maxZ = 100.0;
  68266. /**
  68267. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  68268. * @type {number}
  68269. */
  68270. _this.minZAspect = 0.2;
  68271. /**
  68272. * Number of samples used for the SSAO calculations. Default value is 8
  68273. * @type {number}
  68274. */
  68275. _this._samples = 8;
  68276. /**
  68277. * Are we using bilateral blur ?
  68278. * @type {boolean}
  68279. */
  68280. _this._expensiveBlur = true;
  68281. /**
  68282. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  68283. * @type {number}
  68284. */
  68285. _this.radius = 2.0;
  68286. /**
  68287. * The base color of the SSAO post-process
  68288. * The final result is "base + ssao" between [0, 1]
  68289. * @type {number}
  68290. */
  68291. _this.base = 0.1;
  68292. _this._firstUpdate = true;
  68293. _this._scene = scene;
  68294. if (!_this.isSupported) {
  68295. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  68296. return _this;
  68297. }
  68298. var ssaoRatio = ratio.ssaoRatio || ratio;
  68299. var blurRatio = ratio.blurRatio || ratio;
  68300. // Set up assets
  68301. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  68302. _this._createRandomTexture();
  68303. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  68304. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  68305. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68306. _this._createSSAOPostProcess(1.0);
  68307. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  68308. _this._createSSAOCombinePostProcess(blurRatio);
  68309. // Set up pipeline
  68310. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68311. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68312. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68313. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68314. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68315. // Finish
  68316. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68317. if (cameras)
  68318. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68319. return _this;
  68320. }
  68321. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  68322. get: function () {
  68323. return this._samples;
  68324. },
  68325. set: function (n) {
  68326. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  68327. this._samples = n;
  68328. this._sampleSphere = this._generateHemisphere();
  68329. this._firstUpdate = true;
  68330. },
  68331. enumerable: true,
  68332. configurable: true
  68333. });
  68334. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  68335. get: function () {
  68336. return this._expensiveBlur;
  68337. },
  68338. set: function (b) {
  68339. 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"]);
  68340. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  68341. this._expensiveBlur = b;
  68342. this._firstUpdate = true;
  68343. },
  68344. enumerable: true,
  68345. configurable: true
  68346. });
  68347. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  68348. /**
  68349. * Support test.
  68350. * @type {boolean}
  68351. */
  68352. get: function () {
  68353. var engine = BABYLON.Engine.LastCreatedEngine;
  68354. if (!engine) {
  68355. return false;
  68356. }
  68357. return engine.getCaps().drawBuffersExtension;
  68358. },
  68359. enumerable: true,
  68360. configurable: true
  68361. });
  68362. // Public Methods
  68363. /**
  68364. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68365. */
  68366. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  68367. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  68368. for (var i = 0; i < this._scene.cameras.length; i++) {
  68369. var camera = this._scene.cameras[i];
  68370. this._originalColorPostProcess.dispose(camera);
  68371. this._ssaoPostProcess.dispose(camera);
  68372. this._blurHPostProcess.dispose(camera);
  68373. this._blurVPostProcess.dispose(camera);
  68374. this._ssaoCombinePostProcess.dispose(camera);
  68375. }
  68376. this._randomTexture.dispose();
  68377. if (disableGeometryBufferRenderer)
  68378. this._scene.disableGeometryBufferRenderer();
  68379. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68380. _super.prototype.dispose.call(this);
  68381. };
  68382. // Private Methods
  68383. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  68384. var _this = this;
  68385. this._samplerOffsets = [];
  68386. var expensive = this.expensiveBlur;
  68387. for (var i = -8; i < 8; i++) {
  68388. this._samplerOffsets.push(i * 2 + 0.5);
  68389. }
  68390. 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");
  68391. this._blurHPostProcess.onApply = function (effect) {
  68392. if (!_this._scene.activeCamera) {
  68393. return;
  68394. }
  68395. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  68396. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68397. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68398. effect.setFloat("radius", _this.radius);
  68399. effect.setTexture("depthSampler", _this._depthTexture);
  68400. if (_this._firstUpdate) {
  68401. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68402. }
  68403. };
  68404. 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");
  68405. this._blurVPostProcess.onApply = function (effect) {
  68406. if (!_this._scene.activeCamera) {
  68407. return;
  68408. }
  68409. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  68410. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68411. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68412. effect.setFloat("radius", _this.radius);
  68413. effect.setTexture("depthSampler", _this._depthTexture);
  68414. if (_this._firstUpdate) {
  68415. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68416. _this._firstUpdate = false;
  68417. }
  68418. };
  68419. };
  68420. SSAO2RenderingPipeline.prototype._rebuild = function () {
  68421. this._firstUpdate = true;
  68422. _super.prototype._rebuild.call(this);
  68423. };
  68424. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  68425. var numSamples = this.samples;
  68426. var result = [];
  68427. var vector, scale;
  68428. var rand = function (min, max) {
  68429. return Math.random() * (max - min) + min;
  68430. };
  68431. var i = 0;
  68432. while (i < numSamples) {
  68433. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  68434. vector.normalize();
  68435. scale = i / numSamples;
  68436. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  68437. vector.scaleInPlace(scale);
  68438. result.push(vector.x, vector.y, vector.z);
  68439. i++;
  68440. }
  68441. return result;
  68442. };
  68443. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68444. var _this = this;
  68445. var numSamples = this.samples;
  68446. this._sampleSphere = this._generateHemisphere();
  68447. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  68448. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68449. "base", "range", "projection", "near", "far", "texelSize",
  68450. "xViewport", "yViewport", "maxZ", "minZAspect"
  68451. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68452. this._ssaoPostProcess.onApply = function (effect) {
  68453. if (_this._firstUpdate) {
  68454. effect.setArray3("sampleSphere", _this._sampleSphere);
  68455. effect.setFloat("randTextureTiles", 4.0);
  68456. }
  68457. if (!_this._scene.activeCamera) {
  68458. return;
  68459. }
  68460. effect.setFloat("samplesFactor", 1 / _this.samples);
  68461. effect.setFloat("totalStrength", _this.totalStrength);
  68462. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  68463. effect.setFloat("radius", _this.radius);
  68464. effect.setFloat("maxZ", _this.maxZ);
  68465. effect.setFloat("minZAspect", _this.minZAspect);
  68466. effect.setFloat("base", _this.base);
  68467. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68468. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68469. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  68470. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  68471. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  68472. effect.setTexture("textureSampler", _this._depthTexture);
  68473. effect.setTexture("normalSampler", _this._normalTexture);
  68474. effect.setTexture("randomSampler", _this._randomTexture);
  68475. };
  68476. };
  68477. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68478. var _this = this;
  68479. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68480. this._ssaoCombinePostProcess.onApply = function (effect) {
  68481. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68482. };
  68483. };
  68484. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  68485. var size = 512;
  68486. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68487. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68488. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68489. var context = this._randomTexture.getContext();
  68490. var rand = function (min, max) {
  68491. return Math.random() * (max - min) + min;
  68492. };
  68493. var randVector = BABYLON.Vector3.Zero();
  68494. for (var x = 0; x < size; x++) {
  68495. for (var y = 0; y < size; y++) {
  68496. randVector.x = rand(0.0, 1.0);
  68497. randVector.y = rand(0.0, 1.0);
  68498. randVector.z = 0.0;
  68499. randVector.normalize();
  68500. randVector.scaleInPlace(255);
  68501. randVector.x = Math.floor(randVector.x);
  68502. randVector.y = Math.floor(randVector.y);
  68503. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68504. context.fillRect(x, y, 1, 1);
  68505. }
  68506. }
  68507. this._randomTexture.update(false);
  68508. };
  68509. __decorate([
  68510. BABYLON.serialize()
  68511. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  68512. __decorate([
  68513. BABYLON.serialize()
  68514. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  68515. __decorate([
  68516. BABYLON.serialize()
  68517. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  68518. __decorate([
  68519. BABYLON.serialize("samples")
  68520. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  68521. __decorate([
  68522. BABYLON.serialize("expensiveBlur")
  68523. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  68524. __decorate([
  68525. BABYLON.serialize()
  68526. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  68527. __decorate([
  68528. BABYLON.serialize()
  68529. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  68530. return SSAO2RenderingPipeline;
  68531. }(BABYLON.PostProcessRenderPipeline));
  68532. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  68533. })(BABYLON || (BABYLON = {}));
  68534. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  68535. "use strict";
  68536. // BABYLON.JS Chromatic Aberration GLSL Shader
  68537. // Author: Olivier Guyot
  68538. // Separates very slightly R, G and B colors on the edges of the screen
  68539. // Inspired by Francois Tarlier & Martins Upitis
  68540. var BABYLON;
  68541. (function (BABYLON) {
  68542. var LensRenderingPipeline = /** @class */ (function (_super) {
  68543. __extends(LensRenderingPipeline, _super);
  68544. /**
  68545. * @constructor
  68546. *
  68547. * Effect parameters are as follow:
  68548. * {
  68549. * chromatic_aberration: number; // from 0 to x (1 for realism)
  68550. * edge_blur: number; // from 0 to x (1 for realism)
  68551. * distortion: number; // from 0 to x (1 for realism)
  68552. * grain_amount: number; // from 0 to 1
  68553. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  68554. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  68555. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  68556. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  68557. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  68558. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  68559. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  68560. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  68561. * }
  68562. * Note: if an effect parameter is unset, effect is disabled
  68563. *
  68564. * @param {string} name - The rendering pipeline name
  68565. * @param {object} parameters - An object containing all parameters (see above)
  68566. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68567. * @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)
  68568. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68569. */
  68570. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  68571. if (ratio === void 0) { ratio = 1.0; }
  68572. var _this = _super.call(this, scene.getEngine(), name) || this;
  68573. // Lens effects can be of the following:
  68574. // - chromatic aberration (slight shift of RGB colors)
  68575. // - blur on the edge of the lens
  68576. // - lens distortion
  68577. // - depth-of-field blur & highlights enhancing
  68578. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  68579. // - grain effect (noise or custom texture)
  68580. // Two additional texture samplers are needed:
  68581. // - depth map (for depth-of-field)
  68582. // - grain texture
  68583. /**
  68584. * The chromatic aberration PostProcess id in the pipeline
  68585. * @type {string}
  68586. */
  68587. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  68588. /**
  68589. * The highlights enhancing PostProcess id in the pipeline
  68590. * @type {string}
  68591. */
  68592. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  68593. /**
  68594. * The depth-of-field PostProcess id in the pipeline
  68595. * @type {string}
  68596. */
  68597. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  68598. _this._scene = scene;
  68599. // Fetch texture samplers
  68600. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68601. if (parameters.grain_texture) {
  68602. _this._grainTexture = parameters.grain_texture;
  68603. }
  68604. else {
  68605. _this._createGrainTexture();
  68606. }
  68607. // save parameters
  68608. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  68609. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  68610. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  68611. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  68612. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  68613. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  68614. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  68615. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  68616. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  68617. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  68618. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  68619. // Create effects
  68620. _this._createChromaticAberrationPostProcess(ratio);
  68621. _this._createHighlightsPostProcess(ratio);
  68622. _this._createDepthOfFieldPostProcess(ratio / 4);
  68623. // Set up pipeline
  68624. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  68625. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  68626. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  68627. if (_this._highlightsGain === -1) {
  68628. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  68629. }
  68630. // Finish
  68631. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68632. if (cameras) {
  68633. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68634. }
  68635. return _this;
  68636. }
  68637. // public methods (self explanatory)
  68638. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  68639. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  68640. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  68641. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  68642. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  68643. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  68644. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  68645. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  68646. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  68647. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  68648. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  68649. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  68650. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  68651. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  68652. };
  68653. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  68654. this._highlightsPostProcess.updateEffect();
  68655. };
  68656. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  68657. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  68658. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  68659. this._highlightsGain = amount;
  68660. };
  68661. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  68662. if (this._highlightsGain === -1) {
  68663. this._highlightsGain = 1.0;
  68664. }
  68665. this._highlightsThreshold = amount;
  68666. };
  68667. LensRenderingPipeline.prototype.disableHighlights = function () {
  68668. this._highlightsGain = -1;
  68669. };
  68670. /**
  68671. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  68672. */
  68673. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68674. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68675. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68676. this._chromaticAberrationPostProcess = null;
  68677. this._highlightsPostProcess = null;
  68678. this._depthOfFieldPostProcess = null;
  68679. this._grainTexture.dispose();
  68680. if (disableDepthRender)
  68681. this._scene.disableDepthRenderer();
  68682. };
  68683. // colors shifting and distortion
  68684. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  68685. var _this = this;
  68686. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  68687. [], // samplers
  68688. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68689. this._chromaticAberrationPostProcess.onApply = function (effect) {
  68690. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  68691. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68692. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68693. effect.setFloat('radialIntensity', 1);
  68694. effect.setFloat2('direction', 17, 17);
  68695. effect.setFloat2('centerPosition', 0.5, 0.5);
  68696. };
  68697. };
  68698. // highlights enhancing
  68699. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  68700. var _this = this;
  68701. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  68702. [], // samplers
  68703. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  68704. this._highlightsPostProcess.onApply = function (effect) {
  68705. effect.setFloat('gain', _this._highlightsGain);
  68706. effect.setFloat('threshold', _this._highlightsThreshold);
  68707. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  68708. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68709. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68710. };
  68711. };
  68712. // colors shifting and distortion
  68713. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  68714. var _this = this;
  68715. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  68716. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  68717. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  68718. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68719. this._depthOfFieldPostProcess.onApply = function (effect) {
  68720. effect.setTexture("depthSampler", _this._depthTexture);
  68721. effect.setTexture("grainSampler", _this._grainTexture);
  68722. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  68723. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  68724. effect.setFloat('grain_amount', _this._grainAmount);
  68725. effect.setBool('blur_noise', _this._blurNoise);
  68726. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68727. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68728. effect.setFloat('distortion', _this._distortion);
  68729. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  68730. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  68731. effect.setFloat('aperture', _this._dofAperture);
  68732. effect.setFloat('darken', _this._dofDarken);
  68733. effect.setFloat('edge_blur', _this._edgeBlur);
  68734. effect.setBool('highlights', (_this._highlightsGain !== -1));
  68735. if (_this._scene.activeCamera) {
  68736. effect.setFloat('near', _this._scene.activeCamera.minZ);
  68737. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  68738. }
  68739. };
  68740. };
  68741. // creates a black and white random noise texture, 512x512
  68742. LensRenderingPipeline.prototype._createGrainTexture = function () {
  68743. var size = 512;
  68744. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68745. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68746. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68747. var context = this._grainTexture.getContext();
  68748. var rand = function (min, max) {
  68749. return Math.random() * (max - min) + min;
  68750. };
  68751. var value;
  68752. for (var x = 0; x < size; x++) {
  68753. for (var y = 0; y < size; y++) {
  68754. value = Math.floor(rand(0.42, 0.58) * 255);
  68755. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  68756. context.fillRect(x, y, 1, 1);
  68757. }
  68758. }
  68759. this._grainTexture.update(false);
  68760. };
  68761. return LensRenderingPipeline;
  68762. }(BABYLON.PostProcessRenderPipeline));
  68763. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  68764. })(BABYLON || (BABYLON = {}));
  68765. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  68766. "use strict";
  68767. var BABYLON;
  68768. (function (BABYLON) {
  68769. var StandardRenderingPipeline = /** @class */ (function (_super) {
  68770. __extends(StandardRenderingPipeline, _super);
  68771. /**
  68772. * @constructor
  68773. * @param {string} name - The rendering pipeline name
  68774. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68775. * @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)
  68776. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  68777. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68778. */
  68779. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  68780. if (originalPostProcess === void 0) { originalPostProcess = null; }
  68781. var _this = _super.call(this, scene.getEngine(), name) || this;
  68782. _this.downSampleX4PostProcess = null;
  68783. _this.brightPassPostProcess = null;
  68784. _this.blurHPostProcesses = [];
  68785. _this.blurVPostProcesses = [];
  68786. _this.textureAdderPostProcess = null;
  68787. _this.volumetricLightPostProcess = null;
  68788. _this.volumetricLightSmoothXPostProcess = null;
  68789. _this.volumetricLightSmoothYPostProcess = null;
  68790. _this.volumetricLightMergePostProces = null;
  68791. _this.volumetricLightFinalPostProcess = null;
  68792. _this.luminancePostProcess = null;
  68793. _this.luminanceDownSamplePostProcesses = [];
  68794. _this.hdrPostProcess = null;
  68795. _this.textureAdderFinalPostProcess = null;
  68796. _this.lensFlareFinalPostProcess = null;
  68797. _this.hdrFinalPostProcess = null;
  68798. _this.lensFlarePostProcess = null;
  68799. _this.lensFlareComposePostProcess = null;
  68800. _this.motionBlurPostProcess = null;
  68801. _this.depthOfFieldPostProcess = null;
  68802. // Values
  68803. _this.brightThreshold = 1.0;
  68804. _this.blurWidth = 512.0;
  68805. _this.horizontalBlur = false;
  68806. _this.exposure = 1.0;
  68807. _this.lensTexture = null;
  68808. _this.volumetricLightCoefficient = 0.2;
  68809. _this.volumetricLightPower = 4.0;
  68810. _this.volumetricLightBlurScale = 64.0;
  68811. _this.sourceLight = null;
  68812. _this.hdrMinimumLuminance = 1.0;
  68813. _this.hdrDecreaseRate = 0.5;
  68814. _this.hdrIncreaseRate = 0.5;
  68815. _this.lensColorTexture = null;
  68816. _this.lensFlareStrength = 20.0;
  68817. _this.lensFlareGhostDispersal = 1.4;
  68818. _this.lensFlareHaloWidth = 0.7;
  68819. _this.lensFlareDistortionStrength = 16.0;
  68820. _this.lensStarTexture = null;
  68821. _this.lensFlareDirtTexture = null;
  68822. _this.depthOfFieldDistance = 10.0;
  68823. _this.depthOfFieldBlurWidth = 64.0;
  68824. _this.motionStrength = 1.0;
  68825. // IAnimatable
  68826. _this.animations = [];
  68827. _this._currentDepthOfFieldSource = null;
  68828. _this._hdrCurrentLuminance = 1.0;
  68829. // Getters and setters
  68830. _this._bloomEnabled = true;
  68831. _this._depthOfFieldEnabled = false;
  68832. _this._vlsEnabled = false;
  68833. _this._lensFlareEnabled = false;
  68834. _this._hdrEnabled = false;
  68835. _this._motionBlurEnabled = false;
  68836. _this._motionBlurSamples = 64.0;
  68837. _this._volumetricLightStepsCount = 50.0;
  68838. _this._cameras = cameras || [];
  68839. // Initialize
  68840. _this._scene = scene;
  68841. _this._basePostProcess = originalPostProcess;
  68842. _this._ratio = ratio;
  68843. // Misc
  68844. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68845. // Finish
  68846. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68847. _this._buildPipeline();
  68848. return _this;
  68849. }
  68850. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  68851. get: function () {
  68852. return this._bloomEnabled;
  68853. },
  68854. set: function (enabled) {
  68855. if (this._bloomEnabled === enabled) {
  68856. return;
  68857. }
  68858. this._bloomEnabled = enabled;
  68859. this._buildPipeline();
  68860. },
  68861. enumerable: true,
  68862. configurable: true
  68863. });
  68864. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  68865. get: function () {
  68866. return this._depthOfFieldEnabled;
  68867. },
  68868. set: function (enabled) {
  68869. if (this._depthOfFieldEnabled === enabled) {
  68870. return;
  68871. }
  68872. this._depthOfFieldEnabled = enabled;
  68873. this._buildPipeline();
  68874. },
  68875. enumerable: true,
  68876. configurable: true
  68877. });
  68878. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  68879. get: function () {
  68880. return this._lensFlareEnabled;
  68881. },
  68882. set: function (enabled) {
  68883. if (this._lensFlareEnabled === enabled) {
  68884. return;
  68885. }
  68886. this._lensFlareEnabled = enabled;
  68887. this._buildPipeline();
  68888. },
  68889. enumerable: true,
  68890. configurable: true
  68891. });
  68892. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  68893. get: function () {
  68894. return this._hdrEnabled;
  68895. },
  68896. set: function (enabled) {
  68897. if (this._hdrEnabled === enabled) {
  68898. return;
  68899. }
  68900. this._hdrEnabled = enabled;
  68901. this._buildPipeline();
  68902. },
  68903. enumerable: true,
  68904. configurable: true
  68905. });
  68906. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  68907. get: function () {
  68908. return this._vlsEnabled;
  68909. },
  68910. set: function (enabled) {
  68911. if (this._vlsEnabled === enabled) {
  68912. return;
  68913. }
  68914. if (enabled) {
  68915. var geometry = this._scene.enableGeometryBufferRenderer();
  68916. if (!geometry) {
  68917. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  68918. return;
  68919. }
  68920. }
  68921. this._vlsEnabled = enabled;
  68922. this._buildPipeline();
  68923. },
  68924. enumerable: true,
  68925. configurable: true
  68926. });
  68927. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  68928. get: function () {
  68929. return this._motionBlurEnabled;
  68930. },
  68931. set: function (enabled) {
  68932. if (this._motionBlurEnabled === enabled) {
  68933. return;
  68934. }
  68935. this._motionBlurEnabled = enabled;
  68936. this._buildPipeline();
  68937. },
  68938. enumerable: true,
  68939. configurable: true
  68940. });
  68941. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  68942. get: function () {
  68943. return this._volumetricLightStepsCount;
  68944. },
  68945. set: function (count) {
  68946. if (this.volumetricLightPostProcess) {
  68947. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  68948. }
  68949. this._volumetricLightStepsCount = count;
  68950. },
  68951. enumerable: true,
  68952. configurable: true
  68953. });
  68954. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  68955. get: function () {
  68956. return this._motionBlurSamples;
  68957. },
  68958. set: function (samples) {
  68959. if (this.motionBlurPostProcess) {
  68960. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  68961. }
  68962. this._motionBlurSamples = samples;
  68963. },
  68964. enumerable: true,
  68965. configurable: true
  68966. });
  68967. StandardRenderingPipeline.prototype._buildPipeline = function () {
  68968. var _this = this;
  68969. var ratio = this._ratio;
  68970. var scene = this._scene;
  68971. this._disposePostProcesses();
  68972. this._reset();
  68973. // Create pass post-process
  68974. if (!this._basePostProcess) {
  68975. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  68976. this.originalPostProcess.onApply = function (effect) {
  68977. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  68978. };
  68979. }
  68980. else {
  68981. this.originalPostProcess = this._basePostProcess;
  68982. }
  68983. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  68984. this._currentDepthOfFieldSource = this.originalPostProcess;
  68985. if (this._vlsEnabled) {
  68986. // Create volumetric light
  68987. this._createVolumetricLightPostProcess(scene, ratio);
  68988. // Create volumetric light final post-process
  68989. 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);
  68990. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  68991. }
  68992. if (this._bloomEnabled) {
  68993. // Create down sample X4 post-process
  68994. this._createDownSampleX4PostProcess(scene, ratio / 2);
  68995. // Create bright pass post-process
  68996. this._createBrightPassPostProcess(scene, ratio / 2);
  68997. // Create gaussian blur post-processes (down sampling blurs)
  68998. this._createBlurPostProcesses(scene, ratio / 4, 1);
  68999. // Create texture adder post-process
  69000. this._createTextureAdderPostProcess(scene, ratio);
  69001. // Create depth-of-field source post-process
  69002. 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);
  69003. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  69004. }
  69005. if (this._lensFlareEnabled) {
  69006. // Create lens flare post-process
  69007. this._createLensFlarePostProcess(scene, ratio);
  69008. // Create depth-of-field source post-process post lens-flare and disable it now
  69009. 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);
  69010. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  69011. }
  69012. if (this._hdrEnabled) {
  69013. // Create luminance
  69014. this._createLuminancePostProcesses(scene, this._floatTextureType);
  69015. // Create HDR
  69016. this._createHdrPostProcess(scene, ratio);
  69017. // Create depth-of-field source post-process post hdr and disable it now
  69018. 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);
  69019. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  69020. }
  69021. if (this._depthOfFieldEnabled) {
  69022. // Create gaussian blur used by depth-of-field
  69023. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  69024. // Create depth-of-field post-process
  69025. this._createDepthOfFieldPostProcess(scene, ratio);
  69026. }
  69027. if (this._motionBlurEnabled) {
  69028. // Create motion blur post-process
  69029. this._createMotionBlurPostProcess(scene, ratio);
  69030. }
  69031. if (this._cameras !== null) {
  69032. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69033. }
  69034. };
  69035. // Down Sample X4 Post-Processs
  69036. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  69037. var _this = this;
  69038. var downSampleX4Offsets = new Array(32);
  69039. 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);
  69040. this.downSampleX4PostProcess.onApply = function (effect) {
  69041. var id = 0;
  69042. var width = _this.downSampleX4PostProcess.width;
  69043. var height = _this.downSampleX4PostProcess.height;
  69044. for (var i = -2; i < 2; i++) {
  69045. for (var j = -2; j < 2; j++) {
  69046. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  69047. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  69048. id += 2;
  69049. }
  69050. }
  69051. effect.setArray2("dsOffsets", downSampleX4Offsets);
  69052. };
  69053. // Add to pipeline
  69054. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  69055. };
  69056. // Brightpass Post-Process
  69057. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  69058. var _this = this;
  69059. var brightOffsets = new Array(8);
  69060. 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);
  69061. this.brightPassPostProcess.onApply = function (effect) {
  69062. var sU = (1.0 / _this.brightPassPostProcess.width);
  69063. var sV = (1.0 / _this.brightPassPostProcess.height);
  69064. brightOffsets[0] = -0.5 * sU;
  69065. brightOffsets[1] = 0.5 * sV;
  69066. brightOffsets[2] = 0.5 * sU;
  69067. brightOffsets[3] = 0.5 * sV;
  69068. brightOffsets[4] = -0.5 * sU;
  69069. brightOffsets[5] = -0.5 * sV;
  69070. brightOffsets[6] = 0.5 * sU;
  69071. brightOffsets[7] = -0.5 * sV;
  69072. effect.setArray2("dsOffsets", brightOffsets);
  69073. effect.setFloat("brightThreshold", _this.brightThreshold);
  69074. };
  69075. // Add to pipeline
  69076. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  69077. };
  69078. // Create blur H&V post-processes
  69079. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  69080. var _this = this;
  69081. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  69082. var engine = scene.getEngine();
  69083. 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);
  69084. 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);
  69085. blurX.onActivateObservable.add(function () {
  69086. var dw = blurX.width / engine.getRenderWidth();
  69087. blurX.kernel = _this[blurWidthKey] * dw;
  69088. });
  69089. blurY.onActivateObservable.add(function () {
  69090. var dw = blurY.height / engine.getRenderHeight();
  69091. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  69092. });
  69093. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  69094. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  69095. this.blurHPostProcesses.push(blurX);
  69096. this.blurVPostProcesses.push(blurY);
  69097. };
  69098. // Create texture adder post-process
  69099. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  69100. var _this = this;
  69101. 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);
  69102. this.textureAdderPostProcess.onApply = function (effect) {
  69103. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  69104. effect.setTexture("lensSampler", _this.lensTexture);
  69105. effect.setFloat("exposure", _this.exposure);
  69106. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  69107. };
  69108. // Add to pipeline
  69109. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  69110. };
  69111. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  69112. var _this = this;
  69113. var geometryRenderer = scene.enableGeometryBufferRenderer();
  69114. geometryRenderer.enablePosition = true;
  69115. var geometry = geometryRenderer.getGBuffer();
  69116. // Base post-process
  69117. 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));
  69118. var depthValues = BABYLON.Vector2.Zero();
  69119. this.volumetricLightPostProcess.onApply = function (effect) {
  69120. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  69121. var generator = _this.sourceLight.getShadowGenerator();
  69122. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  69123. effect.setTexture("positionSampler", geometry.textures[2]);
  69124. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  69125. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  69126. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  69127. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  69128. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  69129. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  69130. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  69131. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  69132. effect.setVector2("depthValues", depthValues);
  69133. }
  69134. };
  69135. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  69136. // Smooth
  69137. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  69138. // Merge
  69139. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  69140. this.volumetricLightMergePostProces.onApply = function (effect) {
  69141. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  69142. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  69143. };
  69144. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  69145. };
  69146. // Create luminance
  69147. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  69148. var _this = this;
  69149. // Create luminance
  69150. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  69151. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  69152. var offsets = [];
  69153. this.luminancePostProcess.onApply = function (effect) {
  69154. var sU = (1.0 / _this.luminancePostProcess.width);
  69155. var sV = (1.0 / _this.luminancePostProcess.height);
  69156. offsets[0] = -0.5 * sU;
  69157. offsets[1] = 0.5 * sV;
  69158. offsets[2] = 0.5 * sU;
  69159. offsets[3] = 0.5 * sV;
  69160. offsets[4] = -0.5 * sU;
  69161. offsets[5] = -0.5 * sV;
  69162. offsets[6] = 0.5 * sU;
  69163. offsets[7] = -0.5 * sV;
  69164. effect.setArray2("lumOffsets", offsets);
  69165. };
  69166. // Add to pipeline
  69167. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  69168. // Create down sample luminance
  69169. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  69170. var size = Math.pow(3, i);
  69171. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  69172. if (i === 0) {
  69173. defines += "#define FINAL_DOWN_SAMPLER";
  69174. }
  69175. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  69176. this.luminanceDownSamplePostProcesses.push(postProcess);
  69177. }
  69178. // Create callbacks and add effects
  69179. var lastLuminance = this.luminancePostProcess;
  69180. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  69181. var downSampleOffsets = new Array(18);
  69182. pp.onApply = function (effect) {
  69183. if (!lastLuminance) {
  69184. return;
  69185. }
  69186. var id = 0;
  69187. for (var x = -1; x < 2; x++) {
  69188. for (var y = -1; y < 2; y++) {
  69189. downSampleOffsets[id] = x / lastLuminance.width;
  69190. downSampleOffsets[id + 1] = y / lastLuminance.height;
  69191. id += 2;
  69192. }
  69193. }
  69194. effect.setArray2("dsOffsets", downSampleOffsets);
  69195. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  69196. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69197. lastLuminance = _this.luminancePostProcess;
  69198. }
  69199. else {
  69200. lastLuminance = pp;
  69201. }
  69202. };
  69203. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69204. pp.onAfterRender = function (effect) {
  69205. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  69206. 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);
  69207. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  69208. };
  69209. }
  69210. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  69211. });
  69212. };
  69213. // Create HDR post-process
  69214. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  69215. var _this = this;
  69216. 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);
  69217. var outputLiminance = 1;
  69218. var time = 0;
  69219. var lastTime = 0;
  69220. this.hdrPostProcess.onApply = function (effect) {
  69221. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  69222. time += scene.getEngine().getDeltaTime();
  69223. if (outputLiminance < 0) {
  69224. outputLiminance = _this._hdrCurrentLuminance;
  69225. }
  69226. else {
  69227. var dt = (lastTime - time) / 1000.0;
  69228. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  69229. outputLiminance += _this.hdrDecreaseRate * dt;
  69230. }
  69231. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  69232. outputLiminance -= _this.hdrIncreaseRate * dt;
  69233. }
  69234. else {
  69235. outputLiminance = _this._hdrCurrentLuminance;
  69236. }
  69237. }
  69238. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  69239. effect.setFloat("averageLuminance", outputLiminance);
  69240. lastTime = time;
  69241. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  69242. };
  69243. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  69244. };
  69245. // Create lens flare post-process
  69246. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  69247. var _this = this;
  69248. 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);
  69249. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  69250. this._createBlurPostProcesses(scene, ratio / 4, 2);
  69251. 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);
  69252. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  69253. var resolution = new BABYLON.Vector2(0, 0);
  69254. // Lens flare
  69255. this.lensFlarePostProcess.onApply = function (effect) {
  69256. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  69257. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  69258. effect.setFloat("strength", _this.lensFlareStrength);
  69259. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  69260. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  69261. // Shift
  69262. resolution.x = _this.lensFlarePostProcess.width;
  69263. resolution.y = _this.lensFlarePostProcess.height;
  69264. effect.setVector2("resolution", resolution);
  69265. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  69266. };
  69267. // Compose
  69268. 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);
  69269. 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);
  69270. this.lensFlareComposePostProcess.onApply = function (effect) {
  69271. if (!_this._scene.activeCamera) {
  69272. return;
  69273. }
  69274. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69275. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  69276. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  69277. // Lens start rotation matrix
  69278. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  69279. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  69280. 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));
  69281. camRot *= 4.0;
  69282. 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);
  69283. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  69284. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  69285. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  69286. };
  69287. };
  69288. // Create depth-of-field post-process
  69289. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  69290. var _this = this;
  69291. 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);
  69292. this.depthOfFieldPostProcess.onApply = function (effect) {
  69293. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69294. effect.setTexture("depthSampler", _this._getDepthTexture());
  69295. effect.setFloat("distance", _this.depthOfFieldDistance);
  69296. };
  69297. // Add to pipeline
  69298. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  69299. };
  69300. // Create motion blur post-process
  69301. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  69302. var _this = this;
  69303. 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);
  69304. var motionScale = 0;
  69305. var prevViewProjection = BABYLON.Matrix.Identity();
  69306. var invViewProjection = BABYLON.Matrix.Identity();
  69307. var viewProjection = BABYLON.Matrix.Identity();
  69308. var screenSize = BABYLON.Vector2.Zero();
  69309. this.motionBlurPostProcess.onApply = function (effect) {
  69310. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  69311. viewProjection.invertToRef(invViewProjection);
  69312. effect.setMatrix("inverseViewProjection", invViewProjection);
  69313. effect.setMatrix("prevViewProjection", prevViewProjection);
  69314. prevViewProjection = viewProjection;
  69315. screenSize.x = _this.motionBlurPostProcess.width;
  69316. screenSize.y = _this.motionBlurPostProcess.height;
  69317. effect.setVector2("screenSize", screenSize);
  69318. motionScale = scene.getEngine().getFps() / 60.0;
  69319. effect.setFloat("motionScale", motionScale);
  69320. effect.setFloat("motionStrength", _this.motionStrength);
  69321. effect.setTexture("depthSampler", _this._getDepthTexture());
  69322. };
  69323. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  69324. };
  69325. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  69326. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  69327. var renderer = this._scene.enableGeometryBufferRenderer();
  69328. return renderer.getGBuffer().textures[0];
  69329. }
  69330. return this._scene.enableDepthRenderer().getDepthMap();
  69331. };
  69332. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  69333. for (var i = 0; i < this._cameras.length; i++) {
  69334. var camera = this._cameras[i];
  69335. if (this.originalPostProcess) {
  69336. this.originalPostProcess.dispose(camera);
  69337. }
  69338. if (this.downSampleX4PostProcess) {
  69339. this.downSampleX4PostProcess.dispose(camera);
  69340. }
  69341. if (this.brightPassPostProcess) {
  69342. this.brightPassPostProcess.dispose(camera);
  69343. }
  69344. if (this.textureAdderPostProcess) {
  69345. this.textureAdderPostProcess.dispose(camera);
  69346. }
  69347. if (this.textureAdderFinalPostProcess) {
  69348. this.textureAdderFinalPostProcess.dispose(camera);
  69349. }
  69350. if (this.volumetricLightPostProcess) {
  69351. this.volumetricLightPostProcess.dispose(camera);
  69352. }
  69353. if (this.volumetricLightSmoothXPostProcess) {
  69354. this.volumetricLightSmoothXPostProcess.dispose(camera);
  69355. }
  69356. if (this.volumetricLightSmoothYPostProcess) {
  69357. this.volumetricLightSmoothYPostProcess.dispose(camera);
  69358. }
  69359. if (this.volumetricLightMergePostProces) {
  69360. this.volumetricLightMergePostProces.dispose(camera);
  69361. }
  69362. if (this.volumetricLightFinalPostProcess) {
  69363. this.volumetricLightFinalPostProcess.dispose(camera);
  69364. }
  69365. if (this.lensFlarePostProcess) {
  69366. this.lensFlarePostProcess.dispose(camera);
  69367. }
  69368. if (this.lensFlareComposePostProcess) {
  69369. this.lensFlareComposePostProcess.dispose(camera);
  69370. }
  69371. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  69372. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  69373. }
  69374. if (this.luminancePostProcess) {
  69375. this.luminancePostProcess.dispose(camera);
  69376. }
  69377. if (this.hdrPostProcess) {
  69378. this.hdrPostProcess.dispose(camera);
  69379. }
  69380. if (this.hdrFinalPostProcess) {
  69381. this.hdrFinalPostProcess.dispose(camera);
  69382. }
  69383. if (this.depthOfFieldPostProcess) {
  69384. this.depthOfFieldPostProcess.dispose(camera);
  69385. }
  69386. if (this.motionBlurPostProcess) {
  69387. this.motionBlurPostProcess.dispose(camera);
  69388. }
  69389. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  69390. this.blurHPostProcesses[j].dispose(camera);
  69391. }
  69392. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  69393. this.blurVPostProcesses[j].dispose(camera);
  69394. }
  69395. }
  69396. this.originalPostProcess = null;
  69397. this.downSampleX4PostProcess = null;
  69398. this.brightPassPostProcess = null;
  69399. this.textureAdderPostProcess = null;
  69400. this.textureAdderFinalPostProcess = null;
  69401. this.volumetricLightPostProcess = null;
  69402. this.volumetricLightSmoothXPostProcess = null;
  69403. this.volumetricLightSmoothYPostProcess = null;
  69404. this.volumetricLightMergePostProces = null;
  69405. this.volumetricLightFinalPostProcess = null;
  69406. this.lensFlarePostProcess = null;
  69407. this.lensFlareComposePostProcess = null;
  69408. this.luminancePostProcess = null;
  69409. this.hdrPostProcess = null;
  69410. this.hdrFinalPostProcess = null;
  69411. this.depthOfFieldPostProcess = null;
  69412. this.motionBlurPostProcess = null;
  69413. this.luminanceDownSamplePostProcesses = [];
  69414. this.blurHPostProcesses = [];
  69415. this.blurVPostProcesses = [];
  69416. };
  69417. // Dispose
  69418. StandardRenderingPipeline.prototype.dispose = function () {
  69419. this._disposePostProcesses();
  69420. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69421. _super.prototype.dispose.call(this);
  69422. };
  69423. // Serialize rendering pipeline
  69424. StandardRenderingPipeline.prototype.serialize = function () {
  69425. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69426. serializationObject.customType = "StandardRenderingPipeline";
  69427. return serializationObject;
  69428. };
  69429. /**
  69430. * Static members
  69431. */
  69432. // Parse serialized pipeline
  69433. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69434. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  69435. };
  69436. // Luminance steps
  69437. StandardRenderingPipeline.LuminanceSteps = 6;
  69438. __decorate([
  69439. BABYLON.serialize()
  69440. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  69441. __decorate([
  69442. BABYLON.serialize()
  69443. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  69444. __decorate([
  69445. BABYLON.serialize()
  69446. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  69447. __decorate([
  69448. BABYLON.serialize()
  69449. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  69450. __decorate([
  69451. BABYLON.serializeAsTexture("lensTexture")
  69452. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  69453. __decorate([
  69454. BABYLON.serialize()
  69455. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  69456. __decorate([
  69457. BABYLON.serialize()
  69458. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  69459. __decorate([
  69460. BABYLON.serialize()
  69461. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  69462. __decorate([
  69463. BABYLON.serialize()
  69464. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  69465. __decorate([
  69466. BABYLON.serialize()
  69467. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  69468. __decorate([
  69469. BABYLON.serialize()
  69470. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  69471. __decorate([
  69472. BABYLON.serializeAsTexture("lensColorTexture")
  69473. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  69474. __decorate([
  69475. BABYLON.serialize()
  69476. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  69477. __decorate([
  69478. BABYLON.serialize()
  69479. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  69480. __decorate([
  69481. BABYLON.serialize()
  69482. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  69483. __decorate([
  69484. BABYLON.serialize()
  69485. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  69486. __decorate([
  69487. BABYLON.serializeAsTexture("lensStarTexture")
  69488. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  69489. __decorate([
  69490. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  69491. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  69492. __decorate([
  69493. BABYLON.serialize()
  69494. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  69495. __decorate([
  69496. BABYLON.serialize()
  69497. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  69498. __decorate([
  69499. BABYLON.serialize()
  69500. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  69501. __decorate([
  69502. BABYLON.serialize()
  69503. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  69504. __decorate([
  69505. BABYLON.serialize()
  69506. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  69507. __decorate([
  69508. BABYLON.serialize()
  69509. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  69510. __decorate([
  69511. BABYLON.serialize()
  69512. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  69513. __decorate([
  69514. BABYLON.serialize()
  69515. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  69516. __decorate([
  69517. BABYLON.serialize()
  69518. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  69519. __decorate([
  69520. BABYLON.serialize()
  69521. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  69522. __decorate([
  69523. BABYLON.serialize()
  69524. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  69525. __decorate([
  69526. BABYLON.serialize()
  69527. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  69528. return StandardRenderingPipeline;
  69529. }(BABYLON.PostProcessRenderPipeline));
  69530. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  69531. })(BABYLON || (BABYLON = {}));
  69532. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  69533. "use strict";
  69534. var BABYLON;
  69535. (function (BABYLON) {
  69536. var FxaaPostProcess = /** @class */ (function (_super) {
  69537. __extends(FxaaPostProcess, _super);
  69538. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69539. if (camera === void 0) { camera = null; }
  69540. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69541. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  69542. _this.onApplyObservable.add(function (effect) {
  69543. var texelSize = _this.texelSize;
  69544. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  69545. });
  69546. return _this;
  69547. }
  69548. return FxaaPostProcess;
  69549. }(BABYLON.PostProcess));
  69550. BABYLON.FxaaPostProcess = FxaaPostProcess;
  69551. })(BABYLON || (BABYLON = {}));
  69552. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  69553. "use strict";
  69554. var BABYLON;
  69555. (function (BABYLON) {
  69556. /**
  69557. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  69558. */
  69559. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  69560. __extends(ChromaticAberrationPostProcess, _super);
  69561. /**
  69562. * Creates a new instance of @see ChromaticAberrationPostProcess
  69563. * @param name The name of the effect.
  69564. * @param screenWidth The width of the screen to apply the effect on.
  69565. * @param screenHeight The height of the screen to apply the effect on.
  69566. * @param options The required width/height ratio to downsize to before computing the render pass.
  69567. * @param camera The camera to apply the render pass to.
  69568. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69569. * @param engine The engine which the post process will be applied. (default: current engine)
  69570. * @param reusable If the post process can be reused on the same frame. (default: false)
  69571. * @param textureType Type of textures used when performing the post process. (default: 0)
  69572. * @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)
  69573. */
  69574. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69575. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69576. if (blockCompilation === void 0) { blockCompilation = false; }
  69577. 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;
  69578. /**
  69579. * The amount of seperation of rgb channels (default: 30)
  69580. */
  69581. _this.aberrationAmount = 30;
  69582. /**
  69583. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  69584. */
  69585. _this.radialIntensity = 0;
  69586. /**
  69587. * 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))
  69588. */
  69589. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  69590. /**
  69591. * 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))
  69592. */
  69593. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  69594. _this.onApplyObservable.add(function (effect) {
  69595. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  69596. effect.setFloat('screen_width', screenWidth);
  69597. effect.setFloat('screen_height', screenHeight);
  69598. effect.setFloat('radialIntensity', _this.radialIntensity);
  69599. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  69600. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  69601. });
  69602. return _this;
  69603. }
  69604. return ChromaticAberrationPostProcess;
  69605. }(BABYLON.PostProcess));
  69606. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  69607. })(BABYLON || (BABYLON = {}));
  69608. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  69609. "use strict";
  69610. var BABYLON;
  69611. (function (BABYLON) {
  69612. /**
  69613. * The SharpenPostProcess applies a sharpen kernel to every pixel
  69614. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69615. */
  69616. var SharpenPostProcess = /** @class */ (function (_super) {
  69617. __extends(SharpenPostProcess, _super);
  69618. /**
  69619. * Creates a new instance of @see ConvolutionPostProcess
  69620. * @param name The name of the effect.
  69621. * @param options The required width/height ratio to downsize to before computing the render pass.
  69622. * @param camera The camera to apply the render pass to.
  69623. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69624. * @param engine The engine which the post process will be applied. (default: current engine)
  69625. * @param reusable If the post process can be reused on the same frame. (default: false)
  69626. * @param textureType Type of textures used when performing the post process. (default: 0)
  69627. * @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)
  69628. */
  69629. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69630. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69631. if (blockCompilation === void 0) { blockCompilation = false; }
  69632. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69633. /**
  69634. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  69635. */
  69636. _this.colorAmount = 1.0;
  69637. /**
  69638. * How much sharpness should be applied (default: 0.3)
  69639. */
  69640. _this.edgeAmount = 0.3;
  69641. _this.onApply = function (effect) {
  69642. effect.setFloat2("screenSize", _this.width, _this.height);
  69643. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  69644. };
  69645. return _this;
  69646. }
  69647. return SharpenPostProcess;
  69648. }(BABYLON.PostProcess));
  69649. BABYLON.SharpenPostProcess = SharpenPostProcess;
  69650. })(BABYLON || (BABYLON = {}));
  69651. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  69652. "use strict";
  69653. var BABYLON;
  69654. (function (BABYLON) {
  69655. /**
  69656. * The Blur Post Process which blurs an image based on a kernel and direction.
  69657. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  69658. */
  69659. var BlurPostProcess = /** @class */ (function (_super) {
  69660. __extends(BlurPostProcess, _super);
  69661. /**
  69662. * Creates a new instance of @see BlurPostProcess
  69663. * @param name The name of the effect.
  69664. * @param direction The direction in which to blur the image.
  69665. * @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.
  69666. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69667. * @param camera The camera to apply the render pass to.
  69668. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69669. * @param engine The engine which the post process will be applied. (default: current engine)
  69670. * @param reusable If the post process can be reused on the same frame. (default: false)
  69671. * @param textureType Type of textures used when performing the post process. (default: 0)
  69672. * @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)
  69673. */
  69674. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  69675. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69676. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69677. if (defines === void 0) { defines = ""; }
  69678. if (blockCompilation === void 0) { blockCompilation = false; }
  69679. 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;
  69680. _this.direction = direction;
  69681. _this.blockCompilation = blockCompilation;
  69682. _this._packedFloat = false;
  69683. _this._staticDefines = "";
  69684. _this._staticDefines = defines;
  69685. _this.onApplyObservable.add(function (effect) {
  69686. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  69687. });
  69688. _this.kernel = kernel;
  69689. return _this;
  69690. }
  69691. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  69692. /**
  69693. * Gets the length in pixels of the blur sample region
  69694. */
  69695. get: function () {
  69696. return this._idealKernel;
  69697. },
  69698. /**
  69699. * Sets the length in pixels of the blur sample region
  69700. */
  69701. set: function (v) {
  69702. if (this._idealKernel === v) {
  69703. return;
  69704. }
  69705. v = Math.max(v, 1);
  69706. this._idealKernel = v;
  69707. this._kernel = this._nearestBestKernel(v);
  69708. if (!this.blockCompilation) {
  69709. this._updateParameters();
  69710. }
  69711. },
  69712. enumerable: true,
  69713. configurable: true
  69714. });
  69715. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  69716. /**
  69717. * Gets wether or not the blur is unpacking/repacking floats
  69718. */
  69719. get: function () {
  69720. return this._packedFloat;
  69721. },
  69722. /**
  69723. * Sets wether or not the blur needs to unpack/repack floats
  69724. */
  69725. set: function (v) {
  69726. if (this._packedFloat === v) {
  69727. return;
  69728. }
  69729. this._packedFloat = v;
  69730. if (!this.blockCompilation) {
  69731. this._updateParameters();
  69732. }
  69733. },
  69734. enumerable: true,
  69735. configurable: true
  69736. });
  69737. /**
  69738. * Updates the effect with the current post process compile time values and recompiles the shader.
  69739. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69740. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69741. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69742. * @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
  69743. * @param onCompiled Called when the shader has been compiled.
  69744. * @param onError Called if there is an error when compiling a shader.
  69745. */
  69746. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69747. if (defines === void 0) { defines = null; }
  69748. if (uniforms === void 0) { uniforms = null; }
  69749. if (samplers === void 0) { samplers = null; }
  69750. this._updateParameters(onCompiled, onError);
  69751. };
  69752. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  69753. // Generate sampling offsets and weights
  69754. var N = this._kernel;
  69755. var centerIndex = (N - 1) / 2;
  69756. // Generate Gaussian sampling weights over kernel
  69757. var offsets = [];
  69758. var weights = [];
  69759. var totalWeight = 0;
  69760. for (var i = 0; i < N; i++) {
  69761. var u = i / (N - 1);
  69762. var w = this._gaussianWeight(u * 2.0 - 1);
  69763. offsets[i] = (i - centerIndex);
  69764. weights[i] = w;
  69765. totalWeight += w;
  69766. }
  69767. // Normalize weights
  69768. for (var i = 0; i < weights.length; i++) {
  69769. weights[i] /= totalWeight;
  69770. }
  69771. // Optimize: combine samples to take advantage of hardware linear sampling
  69772. // Walk from left to center, combining pairs (symmetrically)
  69773. var linearSamplingWeights = [];
  69774. var linearSamplingOffsets = [];
  69775. var linearSamplingMap = [];
  69776. for (var i = 0; i <= centerIndex; i += 2) {
  69777. var j = Math.min(i + 1, Math.floor(centerIndex));
  69778. var singleCenterSample = i === j;
  69779. if (singleCenterSample) {
  69780. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69781. }
  69782. else {
  69783. var sharedCell = j === centerIndex;
  69784. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  69785. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  69786. if (offsetLinear === 0) {
  69787. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69788. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  69789. }
  69790. else {
  69791. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  69792. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  69793. }
  69794. }
  69795. }
  69796. for (var i = 0; i < linearSamplingMap.length; i++) {
  69797. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  69798. linearSamplingWeights[i] = linearSamplingMap[i].w;
  69799. }
  69800. // Replace with optimized
  69801. offsets = linearSamplingOffsets;
  69802. weights = linearSamplingWeights;
  69803. // Generate shaders
  69804. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  69805. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  69806. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  69807. var defines = "";
  69808. defines += this._staticDefines;
  69809. for (var i = 0; i < varyingCount; i++) {
  69810. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  69811. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  69812. }
  69813. var depCount = 0;
  69814. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  69815. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  69816. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  69817. depCount++;
  69818. }
  69819. if (this.packedFloat) {
  69820. defines += "#define PACKEDFLOAT 1";
  69821. }
  69822. _super.prototype.updateEffect.call(this, defines, null, null, {
  69823. varyingCount: varyingCount,
  69824. depCount: depCount
  69825. }, onCompiled, onError);
  69826. };
  69827. /**
  69828. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  69829. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  69830. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  69831. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  69832. * The gaps between physical kernels are compensated for in the weighting of the samples
  69833. * @param idealKernel Ideal blur kernel.
  69834. * @return Nearest best kernel.
  69835. */
  69836. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  69837. var v = Math.round(idealKernel);
  69838. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  69839. var k = _a[_i];
  69840. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  69841. return Math.max(k, 3);
  69842. }
  69843. }
  69844. return Math.max(v, 3);
  69845. };
  69846. /**
  69847. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  69848. * @param x The point on the Gaussian distribution to sample.
  69849. * @return the value of the Gaussian function at x.
  69850. */
  69851. BlurPostProcess.prototype._gaussianWeight = function (x) {
  69852. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  69853. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  69854. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  69855. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  69856. // truncated at around 1.3% of peak strength.
  69857. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  69858. var sigma = (1 / 3);
  69859. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  69860. var exponent = -((x * x) / (2.0 * sigma * sigma));
  69861. var weight = (1.0 / denominator) * Math.exp(exponent);
  69862. return weight;
  69863. };
  69864. /**
  69865. * Generates a string that can be used as a floating point number in GLSL.
  69866. * @param x Value to print.
  69867. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  69868. * @return GLSL float string.
  69869. */
  69870. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  69871. if (decimalFigures === void 0) { decimalFigures = 8; }
  69872. return x.toFixed(decimalFigures).replace(/0+$/, '');
  69873. };
  69874. return BlurPostProcess;
  69875. }(BABYLON.PostProcess));
  69876. BABYLON.BlurPostProcess = BlurPostProcess;
  69877. })(BABYLON || (BABYLON = {}));
  69878. //# sourceMappingURL=babylon.blurPostProcess.js.map
  69879. "use strict";
  69880. var BABYLON;
  69881. (function (BABYLON) {
  69882. /**
  69883. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  69884. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  69885. * based on samples that have a large difference in distance than the center pixel.
  69886. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69887. */
  69888. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  69889. __extends(DepthOfFieldBlurPostProcess, _super);
  69890. /**
  69891. * Creates a new instance of @see CircleOfConfusionPostProcess
  69892. * @param name The name of the effect.
  69893. * @param scene The scene the effect belongs to.
  69894. * @param direction The direction the blur should be applied.
  69895. * @param kernel The size of the kernel used to blur.
  69896. * @param options The required width/height ratio to downsize to before computing the render pass.
  69897. * @param camera The camera to apply the render pass to.
  69898. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  69899. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  69900. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69901. * @param engine The engine which the post process will be applied. (default: current engine)
  69902. * @param reusable If the post process can be reused on the same frame. (default: false)
  69903. * @param textureType Type of textures used when performing the post process. (default: 0)
  69904. * @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)
  69905. */
  69906. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  69907. if (imageToBlur === void 0) { imageToBlur = null; }
  69908. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69909. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69910. if (blockCompilation === void 0) { blockCompilation = false; }
  69911. 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;
  69912. _this.direction = direction;
  69913. _this.onApplyObservable.add(function (effect) {
  69914. if (imageToBlur != null) {
  69915. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  69916. }
  69917. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  69918. if (scene.activeCamera) {
  69919. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  69920. }
  69921. });
  69922. return _this;
  69923. }
  69924. return DepthOfFieldBlurPostProcess;
  69925. }(BABYLON.BlurPostProcess));
  69926. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  69927. })(BABYLON || (BABYLON = {}));
  69928. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  69929. "use strict";
  69930. var BABYLON;
  69931. (function (BABYLON) {
  69932. /**
  69933. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  69934. */
  69935. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  69936. __extends(DepthOfFieldMergePostProcess, _super);
  69937. /**
  69938. * Creates a new instance of @see CircleOfConfusionPostProcess
  69939. * @param name The name of the effect.
  69940. * @param original The non-blurred image to be modified
  69941. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  69942. * @param blurSteps Incrimental bluring post processes.
  69943. * @param options The required width/height ratio to downsize to before computing the render pass.
  69944. * @param camera The camera to apply the render pass to.
  69945. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69946. * @param engine The engine which the post process will be applied. (default: current engine)
  69947. * @param reusable If the post process can be reused on the same frame. (default: false)
  69948. * @param textureType Type of textures used when performing the post process. (default: 0)
  69949. * @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)
  69950. */
  69951. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69952. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69953. if (blockCompilation === void 0) { blockCompilation = false; }
  69954. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  69955. _this.blurSteps = blurSteps;
  69956. _this.onApplyObservable.add(function (effect) {
  69957. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  69958. effect.setTextureFromPostProcess("textureSampler", original);
  69959. blurSteps.forEach(function (step, index) {
  69960. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  69961. });
  69962. });
  69963. if (!blockCompilation) {
  69964. _this.updateEffect();
  69965. }
  69966. return _this;
  69967. }
  69968. /**
  69969. * Updates the effect with the current post process compile time values and recompiles the shader.
  69970. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69971. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69972. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69973. * @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
  69974. * @param onCompiled Called when the shader has been compiled.
  69975. * @param onError Called if there is an error when compiling a shader.
  69976. */
  69977. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69978. if (defines === void 0) { defines = null; }
  69979. if (uniforms === void 0) { uniforms = null; }
  69980. if (samplers === void 0) { samplers = null; }
  69981. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  69982. };
  69983. return DepthOfFieldMergePostProcess;
  69984. }(BABYLON.PostProcess));
  69985. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  69986. })(BABYLON || (BABYLON = {}));
  69987. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  69988. "use strict";
  69989. var BABYLON;
  69990. (function (BABYLON) {
  69991. /**
  69992. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  69993. */
  69994. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  69995. __extends(CircleOfConfusionPostProcess, _super);
  69996. /**
  69997. * Creates a new instance of @see CircleOfConfusionPostProcess
  69998. * @param name The name of the effect.
  69999. * @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.
  70000. * @param options The required width/height ratio to downsize to before computing the render pass.
  70001. * @param camera The camera to apply the render pass to.
  70002. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70003. * @param engine The engine which the post process will be applied. (default: current engine)
  70004. * @param reusable If the post process can be reused on the same frame. (default: false)
  70005. * @param textureType Type of textures used when performing the post process. (default: 0)
  70006. * @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)
  70007. */
  70008. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70009. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70010. if (blockCompilation === void 0) { blockCompilation = false; }
  70011. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70012. /**
  70013. * 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.
  70014. */
  70015. _this.lensSize = 50;
  70016. /**
  70017. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70018. */
  70019. _this.fStop = 1.4;
  70020. /**
  70021. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70022. */
  70023. _this.focusDistance = 2000;
  70024. /**
  70025. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  70026. */
  70027. _this.focalLength = 50;
  70028. _this._depthTexture = null;
  70029. _this._depthTexture = depthTexture;
  70030. _this.onApplyObservable.add(function (effect) {
  70031. if (!_this._depthTexture) {
  70032. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  70033. return;
  70034. }
  70035. effect.setTexture("depthSampler", _this._depthTexture);
  70036. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  70037. var aperture = _this.lensSize / _this.fStop;
  70038. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  70039. effect.setFloat('focusDistance', _this.focusDistance);
  70040. effect.setFloat('cocPrecalculation', cocPrecalculation);
  70041. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  70042. });
  70043. return _this;
  70044. }
  70045. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  70046. /**
  70047. * 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.
  70048. */
  70049. set: function (value) {
  70050. this._depthTexture = value;
  70051. },
  70052. enumerable: true,
  70053. configurable: true
  70054. });
  70055. return CircleOfConfusionPostProcess;
  70056. }(BABYLON.PostProcess));
  70057. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  70058. })(BABYLON || (BABYLON = {}));
  70059. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  70060. "use strict";
  70061. var BABYLON;
  70062. (function (BABYLON) {
  70063. /**
  70064. * Specifies the level of max blur that should be applied when using the depth of field effect
  70065. */
  70066. var DepthOfFieldEffectBlurLevel;
  70067. (function (DepthOfFieldEffectBlurLevel) {
  70068. /**
  70069. * Subtle blur
  70070. */
  70071. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  70072. /**
  70073. * Medium blur
  70074. */
  70075. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  70076. /**
  70077. * Large blur
  70078. */
  70079. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  70080. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  70081. ;
  70082. /**
  70083. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  70084. */
  70085. var DepthOfFieldEffect = /** @class */ (function (_super) {
  70086. __extends(DepthOfFieldEffect, _super);
  70087. /**
  70088. * Creates a new instance of @see DepthOfFieldEffect
  70089. * @param scene The scene the effect belongs to.
  70090. * @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.
  70091. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  70092. * @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)
  70093. */
  70094. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  70095. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  70096. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  70097. if (blockCompilation === void 0) { blockCompilation = false; }
  70098. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  70099. return _this._effects;
  70100. }, true) || this;
  70101. _this._effects = [];
  70102. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  70103. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70104. // 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)
  70105. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  70106. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70107. _this._depthOfFieldBlurY = [];
  70108. _this._depthOfFieldBlurX = [];
  70109. var blurCount = 1;
  70110. var kernelSize = 15;
  70111. switch (blurLevel) {
  70112. case DepthOfFieldEffectBlurLevel.High: {
  70113. blurCount = 3;
  70114. kernelSize = 51;
  70115. break;
  70116. }
  70117. case DepthOfFieldEffectBlurLevel.Medium: {
  70118. blurCount = 2;
  70119. kernelSize = 31;
  70120. break;
  70121. }
  70122. default: {
  70123. kernelSize = 15;
  70124. blurCount = 1;
  70125. break;
  70126. }
  70127. }
  70128. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  70129. for (var i = 0; i < blurCount; i++) {
  70130. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70131. blurY.autoClear = false;
  70132. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70133. blurX.autoClear = false;
  70134. _this._depthOfFieldBlurY.push(blurY);
  70135. _this._depthOfFieldBlurX.push(blurX);
  70136. }
  70137. // Merge blurred images with original image based on circleOfConfusion
  70138. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70139. _this._depthOfFieldMerge.autoClear = false;
  70140. // Set all post processes on the effect.
  70141. _this._effects = [_this._circleOfConfusion];
  70142. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  70143. _this._effects.push(_this._depthOfFieldBlurY[i]);
  70144. _this._effects.push(_this._depthOfFieldBlurX[i]);
  70145. }
  70146. _this._effects.push(_this._depthOfFieldMerge);
  70147. return _this;
  70148. }
  70149. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  70150. get: function () {
  70151. return this._circleOfConfusion.focalLength;
  70152. },
  70153. /**
  70154. * The focal the length of the camera used in the effect
  70155. */
  70156. set: function (value) {
  70157. this._circleOfConfusion.focalLength = value;
  70158. },
  70159. enumerable: true,
  70160. configurable: true
  70161. });
  70162. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  70163. get: function () {
  70164. return this._circleOfConfusion.fStop;
  70165. },
  70166. /**
  70167. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70168. */
  70169. set: function (value) {
  70170. this._circleOfConfusion.fStop = value;
  70171. },
  70172. enumerable: true,
  70173. configurable: true
  70174. });
  70175. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  70176. get: function () {
  70177. return this._circleOfConfusion.focusDistance;
  70178. },
  70179. /**
  70180. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70181. */
  70182. set: function (value) {
  70183. this._circleOfConfusion.focusDistance = value;
  70184. },
  70185. enumerable: true,
  70186. configurable: true
  70187. });
  70188. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  70189. get: function () {
  70190. return this._circleOfConfusion.lensSize;
  70191. },
  70192. /**
  70193. * 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.
  70194. */
  70195. set: function (value) {
  70196. this._circleOfConfusion.lensSize = value;
  70197. },
  70198. enumerable: true,
  70199. configurable: true
  70200. });
  70201. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  70202. /**
  70203. * 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.
  70204. */
  70205. set: function (value) {
  70206. this._circleOfConfusion.depthTexture = value;
  70207. },
  70208. enumerable: true,
  70209. configurable: true
  70210. });
  70211. /**
  70212. * Disposes each of the internal effects for a given camera.
  70213. * @param camera The camera to dispose the effect on.
  70214. */
  70215. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  70216. this._circleOfConfusion.dispose(camera);
  70217. this._depthOfFieldBlurX.forEach(function (element) {
  70218. element.dispose(camera);
  70219. });
  70220. this._depthOfFieldBlurY.forEach(function (element) {
  70221. element.dispose(camera);
  70222. });
  70223. this._depthOfFieldMerge.dispose(camera);
  70224. };
  70225. /**
  70226. * Internal
  70227. */
  70228. DepthOfFieldEffect.prototype._updateEffects = function () {
  70229. for (var effect in this._effects) {
  70230. this._effects[effect].updateEffect();
  70231. }
  70232. };
  70233. /**
  70234. * Internal
  70235. * @returns if all the contained post processes are ready.
  70236. */
  70237. DepthOfFieldEffect.prototype._isReady = function () {
  70238. for (var effect in this._effects) {
  70239. if (!this._effects[effect].isReady()) {
  70240. return false;
  70241. }
  70242. }
  70243. return true;
  70244. };
  70245. return DepthOfFieldEffect;
  70246. }(BABYLON.PostProcessRenderEffect));
  70247. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  70248. })(BABYLON || (BABYLON = {}));
  70249. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  70250. "use strict";
  70251. var BABYLON;
  70252. (function (BABYLON) {
  70253. /**
  70254. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  70255. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  70256. */
  70257. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  70258. __extends(DefaultRenderingPipeline, _super);
  70259. /**
  70260. * @constructor
  70261. * @param {string} name - The rendering pipeline name
  70262. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  70263. * @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)
  70264. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  70265. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  70266. */
  70267. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  70268. if (automaticBuild === void 0) { automaticBuild = true; }
  70269. var _this = _super.call(this, scene.getEngine(), name) || this;
  70270. _this._originalCameras = [];
  70271. /**
  70272. * ID of the sharpen post process,
  70273. */
  70274. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  70275. /**
  70276. * ID of the pass post process used for bloom,
  70277. */
  70278. _this.PassPostProcessId = "PassPostProcessEffect";
  70279. /**
  70280. * ID of the highlight post process used for bloom,
  70281. */
  70282. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  70283. /**
  70284. * ID of the blurX post process used for bloom,
  70285. */
  70286. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  70287. /**
  70288. * ID of the blurY post process used for bloom,
  70289. */
  70290. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  70291. /**
  70292. * ID of the copy back post process used for bloom,
  70293. */
  70294. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  70295. /**
  70296. * ID of the image processing post process;
  70297. */
  70298. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  70299. /**
  70300. * ID of the Fast Approximate Anti-Aliasing post process;
  70301. */
  70302. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  70303. /**
  70304. * ID of the final merge post process;
  70305. */
  70306. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  70307. /**
  70308. * ID of the chromatic aberration post process,
  70309. */
  70310. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  70311. /**
  70312. * Animations which can be used to tweak settings over a period of time
  70313. */
  70314. _this.animations = [];
  70315. // Values
  70316. _this._sharpenEnabled = false;
  70317. _this._bloomEnabled = false;
  70318. _this._depthOfFieldEnabled = false;
  70319. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  70320. _this._fxaaEnabled = false;
  70321. _this._msaaEnabled = false;
  70322. _this._imageProcessingEnabled = true;
  70323. _this._bloomScale = 0.6;
  70324. _this._chromaticAberrationEnabled = false;
  70325. _this._buildAllowed = true;
  70326. /**
  70327. * Specifies the size of the bloom blur kernel, relative to the final output size
  70328. */
  70329. _this.bloomKernel = 64;
  70330. /**
  70331. * Specifies the weight of the bloom in the final rendering
  70332. */
  70333. _this._bloomWeight = 0.15;
  70334. _this._prevPostProcess = null;
  70335. _this._prevPrevPostProcess = null;
  70336. _this._cameras = cameras || [];
  70337. _this._originalCameras = _this._cameras.slice();
  70338. _this._buildAllowed = automaticBuild;
  70339. // Initialize
  70340. _this._scene = scene;
  70341. var caps = _this._scene.getEngine().getCaps();
  70342. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  70343. // Misc
  70344. if (_this._hdr) {
  70345. if (caps.textureHalfFloatRender) {
  70346. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70347. }
  70348. else if (caps.textureFloatRender) {
  70349. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70350. }
  70351. }
  70352. else {
  70353. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70354. }
  70355. // Attach
  70356. scene.postProcessRenderPipelineManager.addPipeline(_this);
  70357. var engine = _this._scene.getEngine();
  70358. // Create post processes before hand so they can be modified before enabled.
  70359. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  70360. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70361. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  70362. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  70363. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70364. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  70365. _this._buildPipeline();
  70366. return _this;
  70367. }
  70368. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  70369. get: function () {
  70370. return this._sharpenEnabled;
  70371. },
  70372. /**
  70373. * Enable or disable the sharpen process from the pipeline
  70374. */
  70375. set: function (enabled) {
  70376. if (this._sharpenEnabled === enabled) {
  70377. return;
  70378. }
  70379. this._sharpenEnabled = enabled;
  70380. this._buildPipeline();
  70381. },
  70382. enumerable: true,
  70383. configurable: true
  70384. });
  70385. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  70386. get: function () {
  70387. return this._bloomWeight;
  70388. },
  70389. /**
  70390. * The strength of the bloom.
  70391. */
  70392. set: function (value) {
  70393. if (this._bloomWeight === value) {
  70394. return;
  70395. }
  70396. this._bloomWeight = value;
  70397. if (this._hdr && this.copyBack) {
  70398. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  70399. }
  70400. },
  70401. enumerable: true,
  70402. configurable: true
  70403. });
  70404. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  70405. get: function () {
  70406. return this._bloomScale;
  70407. },
  70408. /**
  70409. * The scale of the bloom, lower value will provide better performance.
  70410. */
  70411. set: function (value) {
  70412. if (this._bloomScale === value) {
  70413. return;
  70414. }
  70415. this._bloomScale = value;
  70416. this._buildPipeline();
  70417. },
  70418. enumerable: true,
  70419. configurable: true
  70420. });
  70421. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  70422. get: function () {
  70423. return this._bloomEnabled;
  70424. },
  70425. /**
  70426. * Enable or disable the bloom from the pipeline
  70427. */
  70428. set: function (enabled) {
  70429. if (this._bloomEnabled === enabled) {
  70430. return;
  70431. }
  70432. this._bloomEnabled = enabled;
  70433. this._buildPipeline();
  70434. },
  70435. enumerable: true,
  70436. configurable: true
  70437. });
  70438. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  70439. /**
  70440. * If the depth of field is enabled.
  70441. */
  70442. get: function () {
  70443. return this._depthOfFieldEnabled;
  70444. },
  70445. set: function (enabled) {
  70446. if (this._depthOfFieldEnabled === enabled) {
  70447. return;
  70448. }
  70449. this._depthOfFieldEnabled = enabled;
  70450. this._buildPipeline();
  70451. },
  70452. enumerable: true,
  70453. configurable: true
  70454. });
  70455. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  70456. /**
  70457. * Blur level of the depth of field effect. (Higher blur will effect performance)
  70458. */
  70459. get: function () {
  70460. return this._depthOfFieldBlurLevel;
  70461. },
  70462. set: function (value) {
  70463. if (this._depthOfFieldBlurLevel === value) {
  70464. return;
  70465. }
  70466. this._depthOfFieldBlurLevel = value;
  70467. // recreate dof and dispose old as this setting is not dynamic
  70468. var oldDof = this.depthOfField;
  70469. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  70470. this.depthOfField.focalLength = oldDof.focalLength;
  70471. this.depthOfField.focusDistance = oldDof.focusDistance;
  70472. this.depthOfField.fStop = oldDof.fStop;
  70473. this.depthOfField.lensSize = oldDof.lensSize;
  70474. for (var i = 0; i < this._cameras.length; i++) {
  70475. oldDof.disposeEffects(this._cameras[i]);
  70476. }
  70477. this._buildPipeline();
  70478. },
  70479. enumerable: true,
  70480. configurable: true
  70481. });
  70482. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  70483. get: function () {
  70484. return this._fxaaEnabled;
  70485. },
  70486. /**
  70487. * If the anti aliasing is enabled.
  70488. */
  70489. set: function (enabled) {
  70490. if (this._fxaaEnabled === enabled) {
  70491. return;
  70492. }
  70493. this._fxaaEnabled = enabled;
  70494. this._buildPipeline();
  70495. },
  70496. enumerable: true,
  70497. configurable: true
  70498. });
  70499. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  70500. get: function () {
  70501. return this._msaaEnabled;
  70502. },
  70503. /**
  70504. * If the multisample anti-aliasing is enabled.
  70505. */
  70506. set: function (enabled) {
  70507. if (this._msaaEnabled === enabled) {
  70508. return;
  70509. }
  70510. this._msaaEnabled = enabled;
  70511. this._buildPipeline();
  70512. },
  70513. enumerable: true,
  70514. configurable: true
  70515. });
  70516. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  70517. get: function () {
  70518. return this._imageProcessingEnabled;
  70519. },
  70520. /**
  70521. * If image processing is enabled.
  70522. */
  70523. set: function (enabled) {
  70524. if (this._imageProcessingEnabled === enabled) {
  70525. return;
  70526. }
  70527. this._imageProcessingEnabled = enabled;
  70528. this._buildPipeline();
  70529. },
  70530. enumerable: true,
  70531. configurable: true
  70532. });
  70533. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  70534. get: function () {
  70535. return this._chromaticAberrationEnabled;
  70536. },
  70537. /**
  70538. * Enable or disable the chromaticAberration process from the pipeline
  70539. */
  70540. set: function (enabled) {
  70541. if (this._chromaticAberrationEnabled === enabled) {
  70542. return;
  70543. }
  70544. this._chromaticAberrationEnabled = enabled;
  70545. this._buildPipeline();
  70546. },
  70547. enumerable: true,
  70548. configurable: true
  70549. });
  70550. /**
  70551. * Force the compilation of the entire pipeline.
  70552. */
  70553. DefaultRenderingPipeline.prototype.prepare = function () {
  70554. var previousState = this._buildAllowed;
  70555. this._buildAllowed = true;
  70556. this._buildPipeline();
  70557. this._buildAllowed = previousState;
  70558. };
  70559. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  70560. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  70561. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  70562. postProcess.autoClear = false;
  70563. }
  70564. else {
  70565. postProcess.autoClear = true;
  70566. }
  70567. if (!skipTextureSharing) {
  70568. if (this._prevPrevPostProcess) {
  70569. postProcess.shareOutputWith(this._prevPrevPostProcess);
  70570. }
  70571. else {
  70572. postProcess.useOwnOutput();
  70573. }
  70574. if (this._prevPostProcess) {
  70575. this._prevPrevPostProcess = this._prevPostProcess;
  70576. }
  70577. this._prevPostProcess = postProcess;
  70578. }
  70579. };
  70580. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  70581. var _this = this;
  70582. if (!this._buildAllowed) {
  70583. return;
  70584. }
  70585. var engine = this._scene.getEngine();
  70586. this._disposePostProcesses();
  70587. if (this._cameras !== null) {
  70588. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70589. // get back cameras to be used to reattach pipeline
  70590. this._cameras = this._originalCameras.slice();
  70591. }
  70592. this._reset();
  70593. this._prevPostProcess = null;
  70594. this._prevPrevPostProcess = null;
  70595. if (this.sharpenEnabled) {
  70596. if (!this.sharpen.isReady()) {
  70597. this.sharpen.updateEffect();
  70598. }
  70599. this.addEffect(this._sharpenEffect);
  70600. this._setAutoClearAndTextureSharing(this.sharpen);
  70601. }
  70602. if (this.depthOfFieldEnabled) {
  70603. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  70604. this.depthOfField.depthTexture = depthTexture;
  70605. if (!this.depthOfField._isReady()) {
  70606. this.depthOfField._updateEffects();
  70607. }
  70608. this.addEffect(this.depthOfField);
  70609. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  70610. }
  70611. if (this.bloomEnabled) {
  70612. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70613. this._setAutoClearAndTextureSharing(this.pass, true);
  70614. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  70615. if (!this._hdr) {
  70616. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70617. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  70618. this.highlights.autoClear = false;
  70619. this.highlights.alwaysForcePOT = true;
  70620. }
  70621. this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70622. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  70623. this.blurX.alwaysForcePOT = true;
  70624. this.blurX.autoClear = false;
  70625. this.blurX.onActivateObservable.add(function () {
  70626. var dw = _this.blurX.width / engine.getRenderWidth(true);
  70627. _this.blurX.kernel = _this.bloomKernel * dw;
  70628. });
  70629. this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70630. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  70631. this.blurY.alwaysForcePOT = true;
  70632. this.blurY.autoClear = false;
  70633. this.blurY.onActivateObservable.add(function () {
  70634. var dh = _this.blurY.height / engine.getRenderHeight(true);
  70635. _this.blurY.kernel = _this.bloomKernel * dh;
  70636. });
  70637. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70638. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  70639. this.copyBack.alwaysForcePOT = true;
  70640. if (this._hdr) {
  70641. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  70642. var w = this.bloomWeight;
  70643. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  70644. }
  70645. else {
  70646. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  70647. }
  70648. this.copyBack.autoClear = false;
  70649. }
  70650. if (this._imageProcessingEnabled) {
  70651. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70652. if (this._hdr) {
  70653. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  70654. }
  70655. else {
  70656. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  70657. }
  70658. }
  70659. if (this._hdr && this.imageProcessing) {
  70660. this.finalMerge = this.imageProcessing;
  70661. }
  70662. else {
  70663. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70664. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  70665. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  70666. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  70667. }
  70668. if (this.bloomEnabled) {
  70669. if (this._hdr) {
  70670. this.copyBack.shareOutputWith(this.blurX);
  70671. if (this.imageProcessing) {
  70672. this.imageProcessing.shareOutputWith(this.pass);
  70673. this.imageProcessing.autoClear = false;
  70674. }
  70675. else {
  70676. this.finalMerge.shareOutputWith(this.pass);
  70677. }
  70678. }
  70679. else {
  70680. this.finalMerge.shareOutputWith(this.pass);
  70681. }
  70682. }
  70683. if (this.fxaaEnabled) {
  70684. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70685. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  70686. this._setAutoClearAndTextureSharing(this.fxaa);
  70687. }
  70688. if (this.chromaticAberrationEnabled) {
  70689. if (!this.chromaticAberration.isReady()) {
  70690. this.chromaticAberration.updateEffect();
  70691. }
  70692. this.addEffect(this._chromaticAberrationEffect);
  70693. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  70694. }
  70695. if (this._cameras !== null) {
  70696. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  70697. }
  70698. if (this.msaaEnabled) {
  70699. if (!this._enableMSAAOnFirstPostProcess()) {
  70700. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  70701. }
  70702. }
  70703. };
  70704. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  70705. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  70706. for (var i = 0; i < this._cameras.length; i++) {
  70707. var camera = this._cameras[i];
  70708. if (this.pass) {
  70709. this.pass.dispose(camera);
  70710. }
  70711. if (this.highlights) {
  70712. this.highlights.dispose(camera);
  70713. }
  70714. if (this.blurX) {
  70715. this.blurX.dispose(camera);
  70716. }
  70717. if (this.blurY) {
  70718. this.blurY.dispose(camera);
  70719. }
  70720. if (this.copyBack) {
  70721. this.copyBack.dispose(camera);
  70722. }
  70723. if (this.imageProcessing) {
  70724. this.imageProcessing.dispose(camera);
  70725. }
  70726. if (this.fxaa) {
  70727. this.fxaa.dispose(camera);
  70728. }
  70729. if (this.finalMerge) {
  70730. this.finalMerge.dispose(camera);
  70731. }
  70732. // These are created in the constructor and should not be disposed on every pipeline change
  70733. if (disposeNonRecreated) {
  70734. if (this.sharpen) {
  70735. this.sharpen.dispose(camera);
  70736. }
  70737. if (this.depthOfField) {
  70738. this.depthOfField.disposeEffects(camera);
  70739. }
  70740. if (this.chromaticAberration) {
  70741. this.chromaticAberration.dispose(camera);
  70742. }
  70743. }
  70744. }
  70745. this.pass = null;
  70746. this.highlights = null;
  70747. this.blurX = null;
  70748. this.blurY = null;
  70749. this.copyBack = null;
  70750. this.imageProcessing = null;
  70751. this.fxaa = null;
  70752. this.finalMerge = null;
  70753. if (disposeNonRecreated) {
  70754. this.sharpen = null;
  70755. this.depthOfField = null;
  70756. this.chromaticAberration = null;
  70757. }
  70758. };
  70759. /**
  70760. * Dispose of the pipeline and stop all post processes
  70761. */
  70762. DefaultRenderingPipeline.prototype.dispose = function () {
  70763. this._disposePostProcesses(true);
  70764. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70765. _super.prototype.dispose.call(this);
  70766. };
  70767. /**
  70768. * Serialize the rendering pipeline (Used when exporting)
  70769. * @returns the serialized object
  70770. */
  70771. DefaultRenderingPipeline.prototype.serialize = function () {
  70772. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  70773. serializationObject.customType = "DefaultRenderingPipeline";
  70774. return serializationObject;
  70775. };
  70776. /**
  70777. * Parse the serialized pipeline
  70778. * @param source Source pipeline.
  70779. * @param scene The scene to load the pipeline to.
  70780. * @param rootUrl The URL of the serialized pipeline.
  70781. * @returns An instantiated pipeline from the serialized object.
  70782. */
  70783. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  70784. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  70785. };
  70786. __decorate([
  70787. BABYLON.serialize()
  70788. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  70789. __decorate([
  70790. BABYLON.serialize()
  70791. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  70792. __decorate([
  70793. BABYLON.serialize()
  70794. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  70795. __decorate([
  70796. BABYLON.serialize()
  70797. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  70798. __decorate([
  70799. BABYLON.serialize()
  70800. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  70801. __decorate([
  70802. BABYLON.serialize()
  70803. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  70804. __decorate([
  70805. BABYLON.serialize()
  70806. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  70807. __decorate([
  70808. BABYLON.serialize()
  70809. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  70810. __decorate([
  70811. BABYLON.serialize()
  70812. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  70813. __decorate([
  70814. BABYLON.serialize()
  70815. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  70816. __decorate([
  70817. BABYLON.serialize()
  70818. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  70819. __decorate([
  70820. BABYLON.serialize()
  70821. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  70822. __decorate([
  70823. BABYLON.serialize()
  70824. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  70825. return DefaultRenderingPipeline;
  70826. }(BABYLON.PostProcessRenderPipeline));
  70827. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  70828. })(BABYLON || (BABYLON = {}));
  70829. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  70830. "use strict";
  70831. var BABYLON;
  70832. (function (BABYLON) {
  70833. /**
  70834. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  70835. */
  70836. var GeometryBufferRenderer = /** @class */ (function () {
  70837. /**
  70838. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  70839. * @param scene The scene the buffer belongs to
  70840. * @param ratio How big is the buffer related to the main canvas.
  70841. */
  70842. function GeometryBufferRenderer(scene, ratio) {
  70843. if (ratio === void 0) { ratio = 1; }
  70844. this._enablePosition = false;
  70845. this._scene = scene;
  70846. this._ratio = ratio;
  70847. // Render target
  70848. this._createRenderTargets();
  70849. }
  70850. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  70851. /**
  70852. * Set the render list (meshes to be rendered) used in the G buffer.
  70853. */
  70854. set: function (meshes) {
  70855. this._multiRenderTarget.renderList = meshes;
  70856. },
  70857. enumerable: true,
  70858. configurable: true
  70859. });
  70860. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  70861. /**
  70862. * Gets wether or not G buffer are supported by the running hardware.
  70863. * This requires draw buffer supports
  70864. */
  70865. get: function () {
  70866. return this._multiRenderTarget.isSupported;
  70867. },
  70868. enumerable: true,
  70869. configurable: true
  70870. });
  70871. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  70872. /**
  70873. * Gets wether or not position are enabled for the G buffer.
  70874. */
  70875. get: function () {
  70876. return this._enablePosition;
  70877. },
  70878. /**
  70879. * Sets wether or not position are enabled for the G buffer.
  70880. */
  70881. set: function (enable) {
  70882. this._enablePosition = enable;
  70883. this.dispose();
  70884. this._createRenderTargets();
  70885. },
  70886. enumerable: true,
  70887. configurable: true
  70888. });
  70889. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  70890. /**
  70891. * Gets the scene associated with the buffer.
  70892. */
  70893. get: function () {
  70894. return this._scene;
  70895. },
  70896. enumerable: true,
  70897. configurable: true
  70898. });
  70899. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  70900. /**
  70901. * Gets the ratio used by the buffer during its creation.
  70902. * How big is the buffer related to the main canvas.
  70903. */
  70904. get: function () {
  70905. return this._ratio;
  70906. },
  70907. enumerable: true,
  70908. configurable: true
  70909. });
  70910. /**
  70911. * Checks wether everything is ready to render a submesh to the G buffer.
  70912. * @param subMesh the submesh to check readiness for
  70913. * @param useInstances is the mesh drawn using instance or not
  70914. * @returns true if ready otherwise false
  70915. */
  70916. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  70917. var material = subMesh.getMaterial();
  70918. if (material && material.disableDepthWrite) {
  70919. return false;
  70920. }
  70921. var defines = [];
  70922. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  70923. var mesh = subMesh.getMesh();
  70924. // Alpha test
  70925. if (material && material.needAlphaTesting()) {
  70926. defines.push("#define ALPHATEST");
  70927. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70928. attribs.push(BABYLON.VertexBuffer.UVKind);
  70929. defines.push("#define UV1");
  70930. }
  70931. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70932. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70933. defines.push("#define UV2");
  70934. }
  70935. }
  70936. // Buffers
  70937. if (this._enablePosition) {
  70938. defines.push("#define POSITION");
  70939. }
  70940. // Bones
  70941. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70942. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70943. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70944. if (mesh.numBoneInfluencers > 4) {
  70945. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70946. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70947. }
  70948. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70949. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  70950. }
  70951. else {
  70952. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70953. }
  70954. // Instances
  70955. if (useInstances) {
  70956. defines.push("#define INSTANCES");
  70957. attribs.push("world0");
  70958. attribs.push("world1");
  70959. attribs.push("world2");
  70960. attribs.push("world3");
  70961. }
  70962. // Get correct effect
  70963. var join = defines.join("\n");
  70964. if (this._cachedDefines !== join) {
  70965. this._cachedDefines = join;
  70966. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  70967. }
  70968. return this._effect.isReady();
  70969. };
  70970. /**
  70971. * Gets the current underlying G Buffer.
  70972. * @returns the buffer
  70973. */
  70974. GeometryBufferRenderer.prototype.getGBuffer = function () {
  70975. return this._multiRenderTarget;
  70976. };
  70977. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  70978. /**
  70979. * Gets the number of samples used to render the buffer (anti aliasing).
  70980. */
  70981. get: function () {
  70982. return this._multiRenderTarget.samples;
  70983. },
  70984. /**
  70985. * Sets the number of samples used to render the buffer (anti aliasing).
  70986. */
  70987. set: function (value) {
  70988. this._multiRenderTarget.samples = value;
  70989. },
  70990. enumerable: true,
  70991. configurable: true
  70992. });
  70993. /**
  70994. * Disposes the renderer and frees up associated resources.
  70995. */
  70996. GeometryBufferRenderer.prototype.dispose = function () {
  70997. this.getGBuffer().dispose();
  70998. };
  70999. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  71000. var _this = this;
  71001. var engine = this._scene.getEngine();
  71002. var count = this._enablePosition ? 3 : 2;
  71003. 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 });
  71004. if (!this.isSupported) {
  71005. return;
  71006. }
  71007. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71008. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71009. this._multiRenderTarget.refreshRate = 1;
  71010. this._multiRenderTarget.renderParticles = false;
  71011. this._multiRenderTarget.renderList = null;
  71012. // set default depth value to 1.0 (far away)
  71013. this._multiRenderTarget.onClearObservable.add(function (engine) {
  71014. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  71015. });
  71016. // Custom render function
  71017. var renderSubMesh = function (subMesh) {
  71018. var mesh = subMesh.getRenderingMesh();
  71019. var scene = _this._scene;
  71020. var engine = scene.getEngine();
  71021. var material = subMesh.getMaterial();
  71022. if (!material) {
  71023. return;
  71024. }
  71025. // Culling
  71026. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  71027. // Managing instances
  71028. var batch = mesh._getInstancesRenderList(subMesh._id);
  71029. if (batch.mustReturn) {
  71030. return;
  71031. }
  71032. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71033. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  71034. engine.enableEffect(_this._effect);
  71035. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  71036. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71037. _this._effect.setMatrix("view", scene.getViewMatrix());
  71038. // Alpha test
  71039. if (material && material.needAlphaTesting()) {
  71040. var alphaTexture = material.getAlphaTestTexture();
  71041. if (alphaTexture) {
  71042. _this._effect.setTexture("diffuseSampler", alphaTexture);
  71043. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71044. }
  71045. }
  71046. // Bones
  71047. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71048. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71049. }
  71050. // Draw
  71051. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  71052. }
  71053. };
  71054. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71055. var index;
  71056. if (depthOnlySubMeshes.length) {
  71057. engine.setColorWrite(false);
  71058. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71059. renderSubMesh(depthOnlySubMeshes.data[index]);
  71060. }
  71061. engine.setColorWrite(true);
  71062. }
  71063. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71064. renderSubMesh(opaqueSubMeshes.data[index]);
  71065. }
  71066. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71067. renderSubMesh(alphaTestSubMeshes.data[index]);
  71068. }
  71069. };
  71070. };
  71071. return GeometryBufferRenderer;
  71072. }());
  71073. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  71074. })(BABYLON || (BABYLON = {}));
  71075. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  71076. "use strict";
  71077. var BABYLON;
  71078. (function (BABYLON) {
  71079. var RefractionPostProcess = /** @class */ (function (_super) {
  71080. __extends(RefractionPostProcess, _super);
  71081. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  71082. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  71083. _this.color = color;
  71084. _this.depth = depth;
  71085. _this.colorLevel = colorLevel;
  71086. _this._ownRefractionTexture = true;
  71087. _this.onActivateObservable.add(function (cam) {
  71088. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  71089. });
  71090. _this.onApplyObservable.add(function (effect) {
  71091. effect.setColor3("baseColor", _this.color);
  71092. effect.setFloat("depth", _this.depth);
  71093. effect.setFloat("colorLevel", _this.colorLevel);
  71094. effect.setTexture("refractionSampler", _this._refTexture);
  71095. });
  71096. return _this;
  71097. }
  71098. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  71099. /**
  71100. * Gets or sets the refraction texture
  71101. * Please note that you are responsible for disposing the texture if you set it manually
  71102. */
  71103. get: function () {
  71104. return this._refTexture;
  71105. },
  71106. set: function (value) {
  71107. if (this._refTexture && this._ownRefractionTexture) {
  71108. this._refTexture.dispose();
  71109. }
  71110. this._refTexture = value;
  71111. this._ownRefractionTexture = false;
  71112. },
  71113. enumerable: true,
  71114. configurable: true
  71115. });
  71116. // Methods
  71117. RefractionPostProcess.prototype.dispose = function (camera) {
  71118. if (this._refTexture && this._ownRefractionTexture) {
  71119. this._refTexture.dispose();
  71120. this._refTexture = null;
  71121. }
  71122. _super.prototype.dispose.call(this, camera);
  71123. };
  71124. return RefractionPostProcess;
  71125. }(BABYLON.PostProcess));
  71126. BABYLON.RefractionPostProcess = RefractionPostProcess;
  71127. })(BABYLON || (BABYLON = {}));
  71128. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  71129. "use strict";
  71130. var BABYLON;
  71131. (function (BABYLON) {
  71132. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  71133. __extends(BlackAndWhitePostProcess, _super);
  71134. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  71135. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  71136. _this.degree = 1;
  71137. _this.onApplyObservable.add(function (effect) {
  71138. effect.setFloat("degree", _this.degree);
  71139. });
  71140. return _this;
  71141. }
  71142. return BlackAndWhitePostProcess;
  71143. }(BABYLON.PostProcess));
  71144. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  71145. })(BABYLON || (BABYLON = {}));
  71146. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  71147. "use strict";
  71148. var BABYLON;
  71149. (function (BABYLON) {
  71150. /**
  71151. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  71152. * input texture to perform effects such as edge detection or sharpening
  71153. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  71154. */
  71155. var ConvolutionPostProcess = /** @class */ (function (_super) {
  71156. __extends(ConvolutionPostProcess, _super);
  71157. /**
  71158. * Creates a new instance of @see ConvolutionPostProcess
  71159. * @param name The name of the effect.
  71160. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  71161. * @param options The required width/height ratio to downsize to before computing the render pass.
  71162. * @param camera The camera to apply the render pass to.
  71163. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71164. * @param engine The engine which the post process will be applied. (default: current engine)
  71165. * @param reusable If the post process can be reused on the same frame. (default: false)
  71166. * @param textureType Type of textures used when performing the post process. (default: 0)
  71167. */
  71168. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  71169. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71170. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71171. _this.kernel = kernel;
  71172. _this.onApply = function (effect) {
  71173. effect.setFloat2("screenSize", _this.width, _this.height);
  71174. effect.setArray("kernel", _this.kernel);
  71175. };
  71176. return _this;
  71177. }
  71178. // Statics
  71179. /**
  71180. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71181. */
  71182. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  71183. /**
  71184. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71185. */
  71186. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  71187. /**
  71188. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71189. */
  71190. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  71191. /**
  71192. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71193. */
  71194. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  71195. /**
  71196. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71197. */
  71198. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  71199. /**
  71200. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71201. */
  71202. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  71203. return ConvolutionPostProcess;
  71204. }(BABYLON.PostProcess));
  71205. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  71206. })(BABYLON || (BABYLON = {}));
  71207. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  71208. "use strict";
  71209. var BABYLON;
  71210. (function (BABYLON) {
  71211. var FilterPostProcess = /** @class */ (function (_super) {
  71212. __extends(FilterPostProcess, _super);
  71213. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  71214. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  71215. _this.kernelMatrix = kernelMatrix;
  71216. _this.onApply = function (effect) {
  71217. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  71218. };
  71219. return _this;
  71220. }
  71221. return FilterPostProcess;
  71222. }(BABYLON.PostProcess));
  71223. BABYLON.FilterPostProcess = FilterPostProcess;
  71224. })(BABYLON || (BABYLON = {}));
  71225. //# sourceMappingURL=babylon.filterPostProcess.js.map
  71226. "use strict";
  71227. var BABYLON;
  71228. (function (BABYLON) {
  71229. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  71230. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  71231. __extends(VolumetricLightScatteringPostProcess, _super);
  71232. /**
  71233. * @constructor
  71234. * @param {string} name - The post-process name
  71235. * @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)
  71236. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  71237. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  71238. * @param {number} samples - The post-process quality, default 100
  71239. * @param {number} samplingMode - The post-process filtering mode
  71240. * @param {BABYLON.Engine} engine - The babylon engine
  71241. * @param {boolean} reusable - If the post-process is reusable
  71242. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  71243. */
  71244. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  71245. if (samples === void 0) { samples = 100; }
  71246. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71247. 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;
  71248. _this._screenCoordinates = BABYLON.Vector2.Zero();
  71249. /**
  71250. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  71251. * @type {Vector3}
  71252. */
  71253. _this.customMeshPosition = BABYLON.Vector3.Zero();
  71254. /**
  71255. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  71256. * @type {boolean}
  71257. */
  71258. _this.useCustomMeshPosition = false;
  71259. /**
  71260. * If the post-process should inverse the light scattering direction
  71261. * @type {boolean}
  71262. */
  71263. _this.invert = true;
  71264. /**
  71265. * Array containing the excluded meshes not rendered in the internal pass
  71266. */
  71267. _this.excludedMeshes = new Array();
  71268. /**
  71269. * Controls the overall intensity of the post-process
  71270. * @type {number}
  71271. */
  71272. _this.exposure = 0.3;
  71273. /**
  71274. * Dissipates each sample's contribution in range [0, 1]
  71275. * @type {number}
  71276. */
  71277. _this.decay = 0.96815;
  71278. /**
  71279. * Controls the overall intensity of each sample
  71280. * @type {number}
  71281. */
  71282. _this.weight = 0.58767;
  71283. /**
  71284. * Controls the density of each sample
  71285. * @type {number}
  71286. */
  71287. _this.density = 0.926;
  71288. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  71289. engine = scene.getEngine();
  71290. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  71291. // Configure mesh
  71292. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  71293. // Configure
  71294. _this._createPass(scene, ratio.passRatio || ratio);
  71295. _this.onActivate = function (camera) {
  71296. if (!_this.isSupported) {
  71297. _this.dispose(camera);
  71298. }
  71299. _this.onActivate = null;
  71300. };
  71301. _this.onApplyObservable.add(function (effect) {
  71302. _this._updateMeshScreenCoordinates(scene);
  71303. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  71304. effect.setFloat("exposure", _this.exposure);
  71305. effect.setFloat("decay", _this.decay);
  71306. effect.setFloat("weight", _this.weight);
  71307. effect.setFloat("density", _this.density);
  71308. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  71309. });
  71310. return _this;
  71311. }
  71312. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  71313. get: function () {
  71314. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71315. return false;
  71316. },
  71317. set: function (useDiffuseColor) {
  71318. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71319. },
  71320. enumerable: true,
  71321. configurable: true
  71322. });
  71323. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  71324. return "VolumetricLightScatteringPostProcess";
  71325. };
  71326. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  71327. var mesh = subMesh.getMesh();
  71328. // Render this.mesh as default
  71329. if (mesh === this.mesh && mesh.material) {
  71330. return mesh.material.isReady(mesh);
  71331. }
  71332. var defines = [];
  71333. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71334. var material = subMesh.getMaterial();
  71335. // Alpha test
  71336. if (material) {
  71337. if (material.needAlphaTesting()) {
  71338. defines.push("#define ALPHATEST");
  71339. }
  71340. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71341. attribs.push(BABYLON.VertexBuffer.UVKind);
  71342. defines.push("#define UV1");
  71343. }
  71344. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71345. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71346. defines.push("#define UV2");
  71347. }
  71348. }
  71349. // Bones
  71350. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71351. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71352. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71353. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71354. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  71355. }
  71356. else {
  71357. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71358. }
  71359. // Instances
  71360. if (useInstances) {
  71361. defines.push("#define INSTANCES");
  71362. attribs.push("world0");
  71363. attribs.push("world1");
  71364. attribs.push("world2");
  71365. attribs.push("world3");
  71366. }
  71367. // Get correct effect
  71368. var join = defines.join("\n");
  71369. if (this._cachedDefines !== join) {
  71370. this._cachedDefines = join;
  71371. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  71372. }
  71373. return this._volumetricLightScatteringPass.isReady();
  71374. };
  71375. /**
  71376. * Sets the new light position for light scattering effect
  71377. * @param {BABYLON.Vector3} The new custom light position
  71378. */
  71379. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  71380. this.customMeshPosition = position;
  71381. };
  71382. /**
  71383. * Returns the light position for light scattering effect
  71384. * @return {BABYLON.Vector3} The custom light position
  71385. */
  71386. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  71387. return this.customMeshPosition;
  71388. };
  71389. /**
  71390. * Disposes the internal assets and detaches the post-process from the camera
  71391. */
  71392. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  71393. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  71394. if (rttIndex !== -1) {
  71395. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  71396. }
  71397. this._volumetricLightScatteringRTT.dispose();
  71398. _super.prototype.dispose.call(this, camera);
  71399. };
  71400. /**
  71401. * Returns the render target texture used by the post-process
  71402. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  71403. */
  71404. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  71405. return this._volumetricLightScatteringRTT;
  71406. };
  71407. // Private methods
  71408. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  71409. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  71410. return true;
  71411. }
  71412. return false;
  71413. };
  71414. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  71415. var _this = this;
  71416. var engine = scene.getEngine();
  71417. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71418. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71419. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71420. this._volumetricLightScatteringRTT.renderList = null;
  71421. this._volumetricLightScatteringRTT.renderParticles = false;
  71422. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  71423. var camera = this.getCamera();
  71424. if (camera) {
  71425. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71426. }
  71427. else {
  71428. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71429. }
  71430. // Custom render function for submeshes
  71431. var renderSubMesh = function (subMesh) {
  71432. var mesh = subMesh.getRenderingMesh();
  71433. if (_this._meshExcluded(mesh)) {
  71434. return;
  71435. }
  71436. var material = subMesh.getMaterial();
  71437. if (!material) {
  71438. return;
  71439. }
  71440. var scene = mesh.getScene();
  71441. var engine = scene.getEngine();
  71442. // Culling
  71443. engine.setState(material.backFaceCulling);
  71444. // Managing instances
  71445. var batch = mesh._getInstancesRenderList(subMesh._id);
  71446. if (batch.mustReturn) {
  71447. return;
  71448. }
  71449. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71450. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  71451. var effect = _this._volumetricLightScatteringPass;
  71452. if (mesh === _this.mesh) {
  71453. if (subMesh.effect) {
  71454. effect = subMesh.effect;
  71455. }
  71456. else {
  71457. effect = material.getEffect();
  71458. }
  71459. }
  71460. engine.enableEffect(effect);
  71461. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  71462. if (mesh === _this.mesh) {
  71463. material.bind(mesh.getWorldMatrix(), mesh);
  71464. }
  71465. else {
  71466. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  71467. // Alpha test
  71468. if (material && material.needAlphaTesting()) {
  71469. var alphaTexture = material.getAlphaTestTexture();
  71470. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  71471. if (alphaTexture) {
  71472. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71473. }
  71474. }
  71475. // Bones
  71476. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71477. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71478. }
  71479. }
  71480. // Draw
  71481. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  71482. }
  71483. };
  71484. // Render target texture callbacks
  71485. var savedSceneClearColor;
  71486. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  71487. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  71488. savedSceneClearColor = scene.clearColor;
  71489. scene.clearColor = sceneClearColor;
  71490. });
  71491. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  71492. scene.clearColor = savedSceneClearColor;
  71493. });
  71494. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71495. var engine = scene.getEngine();
  71496. var index;
  71497. if (depthOnlySubMeshes.length) {
  71498. engine.setColorWrite(false);
  71499. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71500. renderSubMesh(depthOnlySubMeshes.data[index]);
  71501. }
  71502. engine.setColorWrite(true);
  71503. }
  71504. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71505. renderSubMesh(opaqueSubMeshes.data[index]);
  71506. }
  71507. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71508. renderSubMesh(alphaTestSubMeshes.data[index]);
  71509. }
  71510. if (transparentSubMeshes.length) {
  71511. // Sort sub meshes
  71512. for (index = 0; index < transparentSubMeshes.length; index++) {
  71513. var submesh = transparentSubMeshes.data[index];
  71514. var boundingInfo = submesh.getBoundingInfo();
  71515. if (boundingInfo && scene.activeCamera) {
  71516. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  71517. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  71518. }
  71519. }
  71520. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  71521. sortedArray.sort(function (a, b) {
  71522. // Alpha index first
  71523. if (a._alphaIndex > b._alphaIndex) {
  71524. return 1;
  71525. }
  71526. if (a._alphaIndex < b._alphaIndex) {
  71527. return -1;
  71528. }
  71529. // Then distance to camera
  71530. if (a._distanceToCamera < b._distanceToCamera) {
  71531. return 1;
  71532. }
  71533. if (a._distanceToCamera > b._distanceToCamera) {
  71534. return -1;
  71535. }
  71536. return 0;
  71537. });
  71538. // Render sub meshes
  71539. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  71540. for (index = 0; index < sortedArray.length; index++) {
  71541. renderSubMesh(sortedArray[index]);
  71542. }
  71543. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71544. }
  71545. };
  71546. };
  71547. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  71548. var transform = scene.getTransformMatrix();
  71549. var meshPosition;
  71550. if (this.useCustomMeshPosition) {
  71551. meshPosition = this.customMeshPosition;
  71552. }
  71553. else if (this.attachedNode) {
  71554. meshPosition = this.attachedNode.position;
  71555. }
  71556. else {
  71557. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  71558. }
  71559. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  71560. this._screenCoordinates.x = pos.x / this._viewPort.width;
  71561. this._screenCoordinates.y = pos.y / this._viewPort.height;
  71562. if (this.invert)
  71563. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  71564. };
  71565. // Static methods
  71566. /**
  71567. * Creates a default mesh for the Volumeric Light Scattering post-process
  71568. * @param {string} The mesh name
  71569. * @param {BABYLON.Scene} The scene where to create the mesh
  71570. * @return {BABYLON.Mesh} the default mesh
  71571. */
  71572. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  71573. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  71574. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  71575. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  71576. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  71577. mesh.material = material;
  71578. return mesh;
  71579. };
  71580. __decorate([
  71581. BABYLON.serializeAsVector3()
  71582. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  71583. __decorate([
  71584. BABYLON.serialize()
  71585. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  71586. __decorate([
  71587. BABYLON.serialize()
  71588. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  71589. __decorate([
  71590. BABYLON.serializeAsMeshReference()
  71591. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  71592. __decorate([
  71593. BABYLON.serialize()
  71594. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  71595. __decorate([
  71596. BABYLON.serialize()
  71597. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  71598. __decorate([
  71599. BABYLON.serialize()
  71600. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  71601. __decorate([
  71602. BABYLON.serialize()
  71603. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  71604. __decorate([
  71605. BABYLON.serialize()
  71606. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  71607. return VolumetricLightScatteringPostProcess;
  71608. }(BABYLON.PostProcess));
  71609. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  71610. })(BABYLON || (BABYLON = {}));
  71611. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  71612. "use strict";
  71613. //
  71614. // This post-process allows the modification of rendered colors by using
  71615. // a 'look-up table' (LUT). This effect is also called Color Grading.
  71616. //
  71617. // The object needs to be provided an url to a texture containing the color
  71618. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  71619. // Use an image editing software to tweak the LUT to match your needs.
  71620. //
  71621. // For an example of a color LUT, see here:
  71622. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  71623. // For explanations on color grading, see here:
  71624. // http://udn.epicgames.com/Three/ColorGrading.html
  71625. //
  71626. var BABYLON;
  71627. (function (BABYLON) {
  71628. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  71629. __extends(ColorCorrectionPostProcess, _super);
  71630. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  71631. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  71632. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71633. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  71634. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71635. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71636. _this.onApply = function (effect) {
  71637. effect.setTexture("colorTable", _this._colorTableTexture);
  71638. };
  71639. return _this;
  71640. }
  71641. return ColorCorrectionPostProcess;
  71642. }(BABYLON.PostProcess));
  71643. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  71644. })(BABYLON || (BABYLON = {}));
  71645. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  71646. "use strict";
  71647. var BABYLON;
  71648. (function (BABYLON) {
  71649. var TonemappingOperator;
  71650. (function (TonemappingOperator) {
  71651. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  71652. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  71653. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  71654. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  71655. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  71656. ;
  71657. var TonemapPostProcess = /** @class */ (function (_super) {
  71658. __extends(TonemapPostProcess, _super);
  71659. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  71660. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71661. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71662. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  71663. _this._operator = _operator;
  71664. _this.exposureAdjustment = exposureAdjustment;
  71665. var defines = "#define ";
  71666. if (_this._operator === TonemappingOperator.Hable)
  71667. defines += "HABLE_TONEMAPPING";
  71668. else if (_this._operator === TonemappingOperator.Reinhard)
  71669. defines += "REINHARD_TONEMAPPING";
  71670. else if (_this._operator === TonemappingOperator.HejiDawson)
  71671. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  71672. else if (_this._operator === TonemappingOperator.Photographic)
  71673. defines += "PHOTOGRAPHIC_TONEMAPPING";
  71674. //sadly a second call to create the effect.
  71675. _this.updateEffect(defines);
  71676. _this.onApply = function (effect) {
  71677. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  71678. };
  71679. return _this;
  71680. }
  71681. return TonemapPostProcess;
  71682. }(BABYLON.PostProcess));
  71683. BABYLON.TonemapPostProcess = TonemapPostProcess;
  71684. })(BABYLON || (BABYLON = {}));
  71685. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  71686. "use strict";
  71687. var BABYLON;
  71688. (function (BABYLON) {
  71689. var DisplayPassPostProcess = /** @class */ (function (_super) {
  71690. __extends(DisplayPassPostProcess, _super);
  71691. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  71692. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  71693. }
  71694. return DisplayPassPostProcess;
  71695. }(BABYLON.PostProcess));
  71696. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  71697. })(BABYLON || (BABYLON = {}));
  71698. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  71699. "use strict";
  71700. var BABYLON;
  71701. (function (BABYLON) {
  71702. var HighlightsPostProcess = /** @class */ (function (_super) {
  71703. __extends(HighlightsPostProcess, _super);
  71704. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  71705. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71706. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71707. }
  71708. return HighlightsPostProcess;
  71709. }(BABYLON.PostProcess));
  71710. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  71711. })(BABYLON || (BABYLON = {}));
  71712. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  71713. "use strict";
  71714. var BABYLON;
  71715. (function (BABYLON) {
  71716. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  71717. __extends(ImageProcessingPostProcess, _super);
  71718. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  71719. if (camera === void 0) { camera = null; }
  71720. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71721. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  71722. _this._fromLinearSpace = true;
  71723. /**
  71724. * Defines cache preventing GC.
  71725. */
  71726. _this._defines = {
  71727. IMAGEPROCESSING: false,
  71728. VIGNETTE: false,
  71729. VIGNETTEBLENDMODEMULTIPLY: false,
  71730. VIGNETTEBLENDMODEOPAQUE: false,
  71731. TONEMAPPING: false,
  71732. CONTRAST: false,
  71733. COLORCURVES: false,
  71734. COLORGRADING: false,
  71735. COLORGRADING3D: false,
  71736. FROMLINEARSPACE: false,
  71737. SAMPLER3DGREENDEPTH: false,
  71738. SAMPLER3DBGRMAP: false,
  71739. IMAGEPROCESSINGPOSTPROCESS: false,
  71740. EXPOSURE: false,
  71741. GRAIN: false,
  71742. };
  71743. // Setup the configuration as forced by the constructor. This would then not force the
  71744. // scene materials output in linear space and let untouched the default forward pass.
  71745. if (imageProcessingConfiguration) {
  71746. imageProcessingConfiguration.applyByPostProcess = true;
  71747. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  71748. // This will cause the shader to be compiled
  71749. _this.fromLinearSpace = false;
  71750. }
  71751. else {
  71752. _this._attachImageProcessingConfiguration(null, true);
  71753. _this.imageProcessingConfiguration.applyByPostProcess = true;
  71754. }
  71755. _this.onApply = function (effect) {
  71756. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  71757. };
  71758. return _this;
  71759. }
  71760. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  71761. /**
  71762. * Gets the image processing configuration used either in this material.
  71763. */
  71764. get: function () {
  71765. return this._imageProcessingConfiguration;
  71766. },
  71767. /**
  71768. * Sets the Default image processing configuration used either in the this material.
  71769. *
  71770. * If sets to null, the scene one is in use.
  71771. */
  71772. set: function (value) {
  71773. this._attachImageProcessingConfiguration(value);
  71774. },
  71775. enumerable: true,
  71776. configurable: true
  71777. });
  71778. /**
  71779. * Attaches a new image processing configuration to the PBR Material.
  71780. * @param configuration
  71781. */
  71782. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  71783. var _this = this;
  71784. if (doNotBuild === void 0) { doNotBuild = false; }
  71785. if (configuration === this._imageProcessingConfiguration) {
  71786. return;
  71787. }
  71788. // Detaches observer.
  71789. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71790. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71791. }
  71792. // Pick the scene configuration if needed.
  71793. if (!configuration) {
  71794. var scene = null;
  71795. var engine = this.getEngine();
  71796. var camera = this.getCamera();
  71797. if (camera) {
  71798. scene = camera.getScene();
  71799. }
  71800. else if (engine && engine.scenes) {
  71801. var scenes = engine.scenes;
  71802. scene = scenes[scenes.length - 1];
  71803. }
  71804. else {
  71805. scene = BABYLON.Engine.LastCreatedScene;
  71806. }
  71807. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  71808. }
  71809. else {
  71810. this._imageProcessingConfiguration = configuration;
  71811. }
  71812. // Attaches observer.
  71813. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  71814. _this._updateParameters();
  71815. });
  71816. // Ensure the effect will be rebuilt.
  71817. if (!doNotBuild) {
  71818. this._updateParameters();
  71819. }
  71820. };
  71821. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  71822. /**
  71823. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  71824. */
  71825. get: function () {
  71826. return this.imageProcessingConfiguration.colorCurves;
  71827. },
  71828. /**
  71829. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  71830. */
  71831. set: function (value) {
  71832. this.imageProcessingConfiguration.colorCurves = value;
  71833. },
  71834. enumerable: true,
  71835. configurable: true
  71836. });
  71837. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  71838. /**
  71839. * Gets wether the color curves effect is enabled.
  71840. */
  71841. get: function () {
  71842. return this.imageProcessingConfiguration.colorCurvesEnabled;
  71843. },
  71844. /**
  71845. * Sets wether the color curves effect is enabled.
  71846. */
  71847. set: function (value) {
  71848. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  71849. },
  71850. enumerable: true,
  71851. configurable: true
  71852. });
  71853. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  71854. /**
  71855. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71856. */
  71857. get: function () {
  71858. return this.imageProcessingConfiguration.colorGradingTexture;
  71859. },
  71860. /**
  71861. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71862. */
  71863. set: function (value) {
  71864. this.imageProcessingConfiguration.colorGradingTexture = value;
  71865. },
  71866. enumerable: true,
  71867. configurable: true
  71868. });
  71869. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  71870. /**
  71871. * Gets wether the color grading effect is enabled.
  71872. */
  71873. get: function () {
  71874. return this.imageProcessingConfiguration.colorGradingEnabled;
  71875. },
  71876. /**
  71877. * Gets wether the color grading effect is enabled.
  71878. */
  71879. set: function (value) {
  71880. this.imageProcessingConfiguration.colorGradingEnabled = value;
  71881. },
  71882. enumerable: true,
  71883. configurable: true
  71884. });
  71885. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  71886. /**
  71887. * Gets exposure used in the effect.
  71888. */
  71889. get: function () {
  71890. return this.imageProcessingConfiguration.exposure;
  71891. },
  71892. /**
  71893. * Sets exposure used in the effect.
  71894. */
  71895. set: function (value) {
  71896. this.imageProcessingConfiguration.exposure = value;
  71897. },
  71898. enumerable: true,
  71899. configurable: true
  71900. });
  71901. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  71902. /**
  71903. * Gets wether tonemapping is enabled or not.
  71904. */
  71905. get: function () {
  71906. return this._imageProcessingConfiguration.toneMappingEnabled;
  71907. },
  71908. /**
  71909. * Sets wether tonemapping is enabled or not
  71910. */
  71911. set: function (value) {
  71912. this._imageProcessingConfiguration.toneMappingEnabled = value;
  71913. },
  71914. enumerable: true,
  71915. configurable: true
  71916. });
  71917. ;
  71918. ;
  71919. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  71920. /**
  71921. * Gets contrast used in the effect.
  71922. */
  71923. get: function () {
  71924. return this.imageProcessingConfiguration.contrast;
  71925. },
  71926. /**
  71927. * Sets contrast used in the effect.
  71928. */
  71929. set: function (value) {
  71930. this.imageProcessingConfiguration.contrast = value;
  71931. },
  71932. enumerable: true,
  71933. configurable: true
  71934. });
  71935. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  71936. /**
  71937. * Gets Vignette stretch size.
  71938. */
  71939. get: function () {
  71940. return this.imageProcessingConfiguration.vignetteStretch;
  71941. },
  71942. /**
  71943. * Sets Vignette stretch size.
  71944. */
  71945. set: function (value) {
  71946. this.imageProcessingConfiguration.vignetteStretch = value;
  71947. },
  71948. enumerable: true,
  71949. configurable: true
  71950. });
  71951. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  71952. /**
  71953. * Gets Vignette centre X Offset.
  71954. */
  71955. get: function () {
  71956. return this.imageProcessingConfiguration.vignetteCentreX;
  71957. },
  71958. /**
  71959. * Sets Vignette centre X Offset.
  71960. */
  71961. set: function (value) {
  71962. this.imageProcessingConfiguration.vignetteCentreX = value;
  71963. },
  71964. enumerable: true,
  71965. configurable: true
  71966. });
  71967. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  71968. /**
  71969. * Gets Vignette centre Y Offset.
  71970. */
  71971. get: function () {
  71972. return this.imageProcessingConfiguration.vignetteCentreY;
  71973. },
  71974. /**
  71975. * Sets Vignette centre Y Offset.
  71976. */
  71977. set: function (value) {
  71978. this.imageProcessingConfiguration.vignetteCentreY = value;
  71979. },
  71980. enumerable: true,
  71981. configurable: true
  71982. });
  71983. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  71984. /**
  71985. * Gets Vignette weight or intensity of the vignette effect.
  71986. */
  71987. get: function () {
  71988. return this.imageProcessingConfiguration.vignetteWeight;
  71989. },
  71990. /**
  71991. * Sets Vignette weight or intensity of the vignette effect.
  71992. */
  71993. set: function (value) {
  71994. this.imageProcessingConfiguration.vignetteWeight = value;
  71995. },
  71996. enumerable: true,
  71997. configurable: true
  71998. });
  71999. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  72000. /**
  72001. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72002. * if vignetteEnabled is set to true.
  72003. */
  72004. get: function () {
  72005. return this.imageProcessingConfiguration.vignetteColor;
  72006. },
  72007. /**
  72008. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72009. * if vignetteEnabled is set to true.
  72010. */
  72011. set: function (value) {
  72012. this.imageProcessingConfiguration.vignetteColor = value;
  72013. },
  72014. enumerable: true,
  72015. configurable: true
  72016. });
  72017. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  72018. /**
  72019. * Gets Camera field of view used by the Vignette effect.
  72020. */
  72021. get: function () {
  72022. return this.imageProcessingConfiguration.vignetteCameraFov;
  72023. },
  72024. /**
  72025. * Sets Camera field of view used by the Vignette effect.
  72026. */
  72027. set: function (value) {
  72028. this.imageProcessingConfiguration.vignetteCameraFov = value;
  72029. },
  72030. enumerable: true,
  72031. configurable: true
  72032. });
  72033. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  72034. /**
  72035. * Gets the vignette blend mode allowing different kind of effect.
  72036. */
  72037. get: function () {
  72038. return this.imageProcessingConfiguration.vignetteBlendMode;
  72039. },
  72040. /**
  72041. * Sets the vignette blend mode allowing different kind of effect.
  72042. */
  72043. set: function (value) {
  72044. this.imageProcessingConfiguration.vignetteBlendMode = value;
  72045. },
  72046. enumerable: true,
  72047. configurable: true
  72048. });
  72049. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  72050. /**
  72051. * Gets wether the vignette effect is enabled.
  72052. */
  72053. get: function () {
  72054. return this.imageProcessingConfiguration.vignetteEnabled;
  72055. },
  72056. /**
  72057. * Sets wether the vignette effect is enabled.
  72058. */
  72059. set: function (value) {
  72060. this.imageProcessingConfiguration.vignetteEnabled = value;
  72061. },
  72062. enumerable: true,
  72063. configurable: true
  72064. });
  72065. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  72066. /**
  72067. * Gets wether the grain effect is enabled.
  72068. */
  72069. get: function () {
  72070. return this.imageProcessingConfiguration.grainEnabled;
  72071. },
  72072. /**
  72073. * Sets wether the grain effect is enabled.
  72074. */
  72075. set: function (value) {
  72076. this.imageProcessingConfiguration.grainEnabled = value;
  72077. },
  72078. enumerable: true,
  72079. configurable: true
  72080. });
  72081. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  72082. /**
  72083. * Gets the grain effect's intensity.
  72084. */
  72085. get: function () {
  72086. return this.imageProcessingConfiguration.grainIntensity;
  72087. },
  72088. /**
  72089. * Sets the grain effect's intensity.
  72090. */
  72091. set: function (value) {
  72092. this.imageProcessingConfiguration.grainIntensity = value;
  72093. },
  72094. enumerable: true,
  72095. configurable: true
  72096. });
  72097. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  72098. /**
  72099. * Gets wether the grain effect is animated.
  72100. */
  72101. get: function () {
  72102. return this.imageProcessingConfiguration.grainAnimated;
  72103. },
  72104. /**
  72105. * Sets wether the grain effect is animated.
  72106. */
  72107. set: function (value) {
  72108. this.imageProcessingConfiguration.grainAnimated = value;
  72109. },
  72110. enumerable: true,
  72111. configurable: true
  72112. });
  72113. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  72114. /**
  72115. * Gets wether the input of the processing is in Gamma or Linear Space.
  72116. */
  72117. get: function () {
  72118. return this._fromLinearSpace;
  72119. },
  72120. /**
  72121. * Sets wether the input of the processing is in Gamma or Linear Space.
  72122. */
  72123. set: function (value) {
  72124. if (this._fromLinearSpace === value) {
  72125. return;
  72126. }
  72127. this._fromLinearSpace = value;
  72128. this._updateParameters();
  72129. },
  72130. enumerable: true,
  72131. configurable: true
  72132. });
  72133. ImageProcessingPostProcess.prototype.getClassName = function () {
  72134. return "ImageProcessingPostProcess";
  72135. };
  72136. ImageProcessingPostProcess.prototype._updateParameters = function () {
  72137. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  72138. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  72139. var defines = "";
  72140. for (var define in this._defines) {
  72141. if (this._defines[define]) {
  72142. defines += "#define " + define + ";\r\n";
  72143. }
  72144. }
  72145. var samplers = ["textureSampler"];
  72146. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  72147. var uniforms = ["scale"];
  72148. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  72149. this.updateEffect(defines, uniforms, samplers);
  72150. };
  72151. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  72152. _super.prototype.dispose.call(this, camera);
  72153. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  72154. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  72155. }
  72156. this.imageProcessingConfiguration.applyByPostProcess = false;
  72157. };
  72158. __decorate([
  72159. BABYLON.serialize()
  72160. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  72161. return ImageProcessingPostProcess;
  72162. }(BABYLON.PostProcess));
  72163. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  72164. })(BABYLON || (BABYLON = {}));
  72165. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  72166. "use strict";
  72167. var BABYLON;
  72168. (function (BABYLON) {
  72169. var Bone = /** @class */ (function (_super) {
  72170. __extends(Bone, _super);
  72171. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  72172. if (parentBone === void 0) { parentBone = null; }
  72173. if (localMatrix === void 0) { localMatrix = null; }
  72174. if (restPose === void 0) { restPose = null; }
  72175. if (baseMatrix === void 0) { baseMatrix = null; }
  72176. if (index === void 0) { index = null; }
  72177. var _this = _super.call(this, name, skeleton.getScene()) || this;
  72178. _this.name = name;
  72179. _this.children = new Array();
  72180. _this.animations = new Array();
  72181. // Set this value to map this bone to a different index in the transform matrices.
  72182. // Set this value to -1 to exclude the bone from the transform matrices.
  72183. _this._index = null;
  72184. _this._worldTransform = new BABYLON.Matrix();
  72185. _this._absoluteTransform = new BABYLON.Matrix();
  72186. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  72187. _this._scaleMatrix = BABYLON.Matrix.Identity();
  72188. _this._scaleVector = BABYLON.Vector3.One();
  72189. _this._negateScaleChildren = BABYLON.Vector3.One();
  72190. _this._scalingDeterminant = 1;
  72191. _this._skeleton = skeleton;
  72192. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  72193. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  72194. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  72195. _this._index = index;
  72196. skeleton.bones.push(_this);
  72197. _this.setParent(parentBone, false);
  72198. _this._updateDifferenceMatrix();
  72199. return _this;
  72200. }
  72201. Object.defineProperty(Bone.prototype, "_matrix", {
  72202. get: function () {
  72203. return this._localMatrix;
  72204. },
  72205. set: function (val) {
  72206. if (this._localMatrix) {
  72207. this._localMatrix.copyFrom(val);
  72208. }
  72209. else {
  72210. this._localMatrix = val;
  72211. }
  72212. },
  72213. enumerable: true,
  72214. configurable: true
  72215. });
  72216. // Members
  72217. Bone.prototype.getSkeleton = function () {
  72218. return this._skeleton;
  72219. };
  72220. Bone.prototype.getParent = function () {
  72221. return this._parent;
  72222. };
  72223. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  72224. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72225. if (this._parent === parent) {
  72226. return;
  72227. }
  72228. if (this._parent) {
  72229. var index = this._parent.children.indexOf(this);
  72230. if (index !== -1) {
  72231. this._parent.children.splice(index, 1);
  72232. }
  72233. }
  72234. this._parent = parent;
  72235. if (this._parent) {
  72236. this._parent.children.push(this);
  72237. }
  72238. if (updateDifferenceMatrix) {
  72239. this._updateDifferenceMatrix();
  72240. }
  72241. };
  72242. Bone.prototype.getLocalMatrix = function () {
  72243. return this._localMatrix;
  72244. };
  72245. Bone.prototype.getBaseMatrix = function () {
  72246. return this._baseMatrix;
  72247. };
  72248. Bone.prototype.getRestPose = function () {
  72249. return this._restPose;
  72250. };
  72251. Bone.prototype.returnToRest = function () {
  72252. this.updateMatrix(this._restPose.clone());
  72253. };
  72254. Bone.prototype.getWorldMatrix = function () {
  72255. return this._worldTransform;
  72256. };
  72257. Bone.prototype.getInvertedAbsoluteTransform = function () {
  72258. return this._invertedAbsoluteTransform;
  72259. };
  72260. Bone.prototype.getAbsoluteTransform = function () {
  72261. return this._absoluteTransform;
  72262. };
  72263. Object.defineProperty(Bone.prototype, "position", {
  72264. // Properties (matches AbstractMesh properties)
  72265. get: function () {
  72266. return this.getPosition();
  72267. },
  72268. set: function (newPosition) {
  72269. this.setPosition(newPosition);
  72270. },
  72271. enumerable: true,
  72272. configurable: true
  72273. });
  72274. Object.defineProperty(Bone.prototype, "rotation", {
  72275. get: function () {
  72276. return this.getRotation();
  72277. },
  72278. set: function (newRotation) {
  72279. this.setRotation(newRotation);
  72280. },
  72281. enumerable: true,
  72282. configurable: true
  72283. });
  72284. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  72285. get: function () {
  72286. return this.getRotationQuaternion();
  72287. },
  72288. set: function (newRotation) {
  72289. this.setRotationQuaternion(newRotation);
  72290. },
  72291. enumerable: true,
  72292. configurable: true
  72293. });
  72294. Object.defineProperty(Bone.prototype, "scaling", {
  72295. get: function () {
  72296. return this.getScale();
  72297. },
  72298. set: function (newScaling) {
  72299. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  72300. },
  72301. enumerable: true,
  72302. configurable: true
  72303. });
  72304. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  72305. /**
  72306. * Gets the animation properties override
  72307. */
  72308. get: function () {
  72309. return this._skeleton.animationPropertiesOverride;
  72310. },
  72311. enumerable: true,
  72312. configurable: true
  72313. });
  72314. // Methods
  72315. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  72316. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72317. this._baseMatrix = matrix.clone();
  72318. this._localMatrix = matrix.clone();
  72319. this._skeleton._markAsDirty();
  72320. if (updateDifferenceMatrix) {
  72321. this._updateDifferenceMatrix();
  72322. }
  72323. };
  72324. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  72325. if (!rootMatrix) {
  72326. rootMatrix = this._baseMatrix;
  72327. }
  72328. if (this._parent) {
  72329. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72330. }
  72331. else {
  72332. this._absoluteTransform.copyFrom(rootMatrix);
  72333. }
  72334. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  72335. for (var index = 0; index < this.children.length; index++) {
  72336. this.children[index]._updateDifferenceMatrix();
  72337. }
  72338. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  72339. };
  72340. Bone.prototype.markAsDirty = function () {
  72341. this._currentRenderId++;
  72342. this._skeleton._markAsDirty();
  72343. };
  72344. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  72345. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72346. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  72347. // all animation may be coming from a library skeleton, so may need to create animation
  72348. if (this.animations.length === 0) {
  72349. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  72350. this.animations[0].setKeys([]);
  72351. }
  72352. // get animation info / verify there is such a range from the source bone
  72353. var sourceRange = source.animations[0].getRange(rangeName);
  72354. if (!sourceRange) {
  72355. return false;
  72356. }
  72357. var from = sourceRange.from;
  72358. var to = sourceRange.to;
  72359. var sourceKeys = source.animations[0].getKeys();
  72360. // rescaling prep
  72361. var sourceBoneLength = source.length;
  72362. var sourceParent = source.getParent();
  72363. var parent = this.getParent();
  72364. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  72365. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  72366. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  72367. var destKeys = this.animations[0].getKeys();
  72368. // loop vars declaration
  72369. var orig;
  72370. var origTranslation;
  72371. var mat;
  72372. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  72373. orig = sourceKeys[key];
  72374. if (orig.frame >= from && orig.frame <= to) {
  72375. if (rescaleAsRequired) {
  72376. mat = orig.value.clone();
  72377. // scale based on parent ratio, when bone has parent
  72378. if (parentScalingReqd) {
  72379. origTranslation = mat.getTranslation();
  72380. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  72381. // scale based on skeleton dimension ratio when root bone, and value is passed
  72382. }
  72383. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  72384. origTranslation = mat.getTranslation();
  72385. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  72386. // use original when root bone, and no data for skelDimensionsRatio
  72387. }
  72388. else {
  72389. mat = orig.value;
  72390. }
  72391. }
  72392. else {
  72393. mat = orig.value;
  72394. }
  72395. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  72396. }
  72397. }
  72398. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  72399. return true;
  72400. };
  72401. /**
  72402. * Translate the bone in local or world space.
  72403. * @param vec The amount to translate the bone.
  72404. * @param space The space that the translation is in.
  72405. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72406. */
  72407. Bone.prototype.translate = function (vec, space, mesh) {
  72408. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72409. var lm = this.getLocalMatrix();
  72410. if (space == BABYLON.Space.LOCAL) {
  72411. lm.m[12] += vec.x;
  72412. lm.m[13] += vec.y;
  72413. lm.m[14] += vec.z;
  72414. }
  72415. else {
  72416. var wm = null;
  72417. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72418. if (mesh) {
  72419. wm = mesh.getWorldMatrix();
  72420. }
  72421. this._skeleton.computeAbsoluteTransforms();
  72422. var tmat = Bone._tmpMats[0];
  72423. var tvec = Bone._tmpVecs[0];
  72424. if (this._parent) {
  72425. if (mesh && wm) {
  72426. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72427. tmat.multiplyToRef(wm, tmat);
  72428. }
  72429. else {
  72430. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72431. }
  72432. }
  72433. tmat.m[12] = 0;
  72434. tmat.m[13] = 0;
  72435. tmat.m[14] = 0;
  72436. tmat.invert();
  72437. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  72438. lm.m[12] += tvec.x;
  72439. lm.m[13] += tvec.y;
  72440. lm.m[14] += tvec.z;
  72441. }
  72442. this.markAsDirty();
  72443. };
  72444. /**
  72445. * Set the postion of the bone in local or world space.
  72446. * @param position The position to set the bone.
  72447. * @param space The space that the position is in.
  72448. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72449. */
  72450. Bone.prototype.setPosition = function (position, space, mesh) {
  72451. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72452. var lm = this.getLocalMatrix();
  72453. if (space == BABYLON.Space.LOCAL) {
  72454. lm.m[12] = position.x;
  72455. lm.m[13] = position.y;
  72456. lm.m[14] = position.z;
  72457. }
  72458. else {
  72459. var wm = null;
  72460. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72461. if (mesh) {
  72462. wm = mesh.getWorldMatrix();
  72463. }
  72464. this._skeleton.computeAbsoluteTransforms();
  72465. var tmat = Bone._tmpMats[0];
  72466. var vec = Bone._tmpVecs[0];
  72467. if (this._parent) {
  72468. if (mesh && wm) {
  72469. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72470. tmat.multiplyToRef(wm, tmat);
  72471. }
  72472. else {
  72473. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72474. }
  72475. }
  72476. tmat.invert();
  72477. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  72478. lm.m[12] = vec.x;
  72479. lm.m[13] = vec.y;
  72480. lm.m[14] = vec.z;
  72481. }
  72482. this.markAsDirty();
  72483. };
  72484. /**
  72485. * Set the absolute postion of the bone (world space).
  72486. * @param position The position to set the bone.
  72487. * @param mesh The mesh that this bone is attached to.
  72488. */
  72489. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  72490. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  72491. };
  72492. /**
  72493. * Set the scale of the bone on the x, y and z axes.
  72494. * @param x The scale of the bone on the x axis.
  72495. * @param x The scale of the bone on the y axis.
  72496. * @param z The scale of the bone on the z axis.
  72497. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72498. */
  72499. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  72500. if (scaleChildren === void 0) { scaleChildren = false; }
  72501. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  72502. if (!scaleChildren) {
  72503. this._negateScaleChildren.x = 1 / x;
  72504. this._negateScaleChildren.y = 1 / y;
  72505. this._negateScaleChildren.z = 1 / z;
  72506. }
  72507. this._syncScaleVector();
  72508. }
  72509. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  72510. };
  72511. /**
  72512. * Scale the bone on the x, y and z axes.
  72513. * @param x The amount to scale the bone on the x axis.
  72514. * @param x The amount to scale the bone on the y axis.
  72515. * @param z The amount to scale the bone on the z axis.
  72516. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72517. */
  72518. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  72519. if (scaleChildren === void 0) { scaleChildren = false; }
  72520. var locMat = this.getLocalMatrix();
  72521. var origLocMat = Bone._tmpMats[0];
  72522. origLocMat.copyFrom(locMat);
  72523. var origLocMatInv = Bone._tmpMats[1];
  72524. origLocMatInv.copyFrom(origLocMat);
  72525. origLocMatInv.invert();
  72526. var scaleMat = Bone._tmpMats[2];
  72527. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  72528. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  72529. this._scaleVector.x *= x;
  72530. this._scaleVector.y *= y;
  72531. this._scaleVector.z *= z;
  72532. locMat.multiplyToRef(origLocMatInv, locMat);
  72533. locMat.multiplyToRef(scaleMat, locMat);
  72534. locMat.multiplyToRef(origLocMat, locMat);
  72535. var parent = this.getParent();
  72536. if (parent) {
  72537. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  72538. }
  72539. else {
  72540. this.getAbsoluteTransform().copyFrom(locMat);
  72541. }
  72542. var len = this.children.length;
  72543. scaleMat.invert();
  72544. for (var i = 0; i < len; i++) {
  72545. var child = this.children[i];
  72546. var cm = child.getLocalMatrix();
  72547. cm.multiplyToRef(scaleMat, cm);
  72548. var lm = child.getLocalMatrix();
  72549. lm.m[12] *= x;
  72550. lm.m[13] *= y;
  72551. lm.m[14] *= z;
  72552. }
  72553. this.computeAbsoluteTransforms();
  72554. if (scaleChildren) {
  72555. for (var i = 0; i < len; i++) {
  72556. this.children[i].scale(x, y, z, scaleChildren);
  72557. }
  72558. }
  72559. this.markAsDirty();
  72560. };
  72561. /**
  72562. * Set the yaw, pitch, and roll of the bone in local or world space.
  72563. * @param yaw The rotation of the bone on the y axis.
  72564. * @param pitch The rotation of the bone on the x axis.
  72565. * @param roll The rotation of the bone on the z axis.
  72566. * @param space The space that the axes of rotation are in.
  72567. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72568. */
  72569. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  72570. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72571. var rotMat = Bone._tmpMats[0];
  72572. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  72573. var rotMatInv = Bone._tmpMats[1];
  72574. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72575. rotMatInv.multiplyToRef(rotMat, rotMat);
  72576. this._rotateWithMatrix(rotMat, space, mesh);
  72577. };
  72578. /**
  72579. * Rotate the bone on an axis in local or world space.
  72580. * @param axis The axis to rotate the bone on.
  72581. * @param amount The amount to rotate the bone.
  72582. * @param space The space that the axis is in.
  72583. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72584. */
  72585. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  72586. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72587. var rmat = Bone._tmpMats[0];
  72588. rmat.m[12] = 0;
  72589. rmat.m[13] = 0;
  72590. rmat.m[14] = 0;
  72591. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  72592. this._rotateWithMatrix(rmat, space, mesh);
  72593. };
  72594. /**
  72595. * Set the rotation of the bone to a particular axis angle in local or world space.
  72596. * @param axis The axis to rotate the bone on.
  72597. * @param angle The angle that the bone should be rotated to.
  72598. * @param space The space that the axis is in.
  72599. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72600. */
  72601. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  72602. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72603. var rotMat = Bone._tmpMats[0];
  72604. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  72605. var rotMatInv = Bone._tmpMats[1];
  72606. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72607. rotMatInv.multiplyToRef(rotMat, rotMat);
  72608. this._rotateWithMatrix(rotMat, space, mesh);
  72609. };
  72610. /**
  72611. * Set the euler rotation of the bone in local of world space.
  72612. * @param rotation The euler rotation that the bone should be set to.
  72613. * @param space The space that the rotation is in.
  72614. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72615. */
  72616. Bone.prototype.setRotation = function (rotation, space, mesh) {
  72617. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72618. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  72619. };
  72620. /**
  72621. * Set the quaternion rotation of the bone in local of world space.
  72622. * @param quat The quaternion rotation that the bone should be set to.
  72623. * @param space The space that the rotation is in.
  72624. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72625. */
  72626. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  72627. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72628. var rotMatInv = Bone._tmpMats[0];
  72629. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72630. var rotMat = Bone._tmpMats[1];
  72631. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  72632. rotMatInv.multiplyToRef(rotMat, rotMat);
  72633. this._rotateWithMatrix(rotMat, space, mesh);
  72634. };
  72635. /**
  72636. * Set the rotation matrix of the bone in local of world space.
  72637. * @param rotMat The rotation matrix that the bone should be set to.
  72638. * @param space The space that the rotation is in.
  72639. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72640. */
  72641. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  72642. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72643. var rotMatInv = Bone._tmpMats[0];
  72644. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72645. var rotMat2 = Bone._tmpMats[1];
  72646. rotMat2.copyFrom(rotMat);
  72647. rotMatInv.multiplyToRef(rotMat, rotMat2);
  72648. this._rotateWithMatrix(rotMat2, space, mesh);
  72649. };
  72650. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  72651. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72652. var lmat = this.getLocalMatrix();
  72653. var lx = lmat.m[12];
  72654. var ly = lmat.m[13];
  72655. var lz = lmat.m[14];
  72656. var parent = this.getParent();
  72657. var parentScale = Bone._tmpMats[3];
  72658. var parentScaleInv = Bone._tmpMats[4];
  72659. if (parent) {
  72660. if (space == BABYLON.Space.WORLD) {
  72661. if (mesh) {
  72662. parentScale.copyFrom(mesh.getWorldMatrix());
  72663. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  72664. }
  72665. else {
  72666. parentScale.copyFrom(parent.getAbsoluteTransform());
  72667. }
  72668. }
  72669. else {
  72670. parentScale = parent._scaleMatrix;
  72671. }
  72672. parentScaleInv.copyFrom(parentScale);
  72673. parentScaleInv.invert();
  72674. lmat.multiplyToRef(parentScale, lmat);
  72675. lmat.multiplyToRef(rmat, lmat);
  72676. lmat.multiplyToRef(parentScaleInv, lmat);
  72677. }
  72678. else {
  72679. if (space == BABYLON.Space.WORLD && mesh) {
  72680. parentScale.copyFrom(mesh.getWorldMatrix());
  72681. parentScaleInv.copyFrom(parentScale);
  72682. parentScaleInv.invert();
  72683. lmat.multiplyToRef(parentScale, lmat);
  72684. lmat.multiplyToRef(rmat, lmat);
  72685. lmat.multiplyToRef(parentScaleInv, lmat);
  72686. }
  72687. else {
  72688. lmat.multiplyToRef(rmat, lmat);
  72689. }
  72690. }
  72691. lmat.m[12] = lx;
  72692. lmat.m[13] = ly;
  72693. lmat.m[14] = lz;
  72694. this.computeAbsoluteTransforms();
  72695. this.markAsDirty();
  72696. };
  72697. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  72698. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72699. if (space == BABYLON.Space.WORLD) {
  72700. var scaleMatrix = Bone._tmpMats[2];
  72701. scaleMatrix.copyFrom(this._scaleMatrix);
  72702. rotMatInv.copyFrom(this.getAbsoluteTransform());
  72703. if (mesh) {
  72704. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  72705. var meshScale = Bone._tmpMats[3];
  72706. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  72707. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  72708. }
  72709. rotMatInv.invert();
  72710. scaleMatrix.m[0] *= this._scalingDeterminant;
  72711. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  72712. }
  72713. else {
  72714. rotMatInv.copyFrom(this.getLocalMatrix());
  72715. rotMatInv.invert();
  72716. var scaleMatrix = Bone._tmpMats[2];
  72717. scaleMatrix.copyFrom(this._scaleMatrix);
  72718. if (this._parent) {
  72719. var pscaleMatrix = Bone._tmpMats[3];
  72720. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  72721. pscaleMatrix.invert();
  72722. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  72723. }
  72724. else {
  72725. scaleMatrix.m[0] *= this._scalingDeterminant;
  72726. }
  72727. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  72728. }
  72729. };
  72730. /**
  72731. * Get the scale of the bone
  72732. * @returns the scale of the bone
  72733. */
  72734. Bone.prototype.getScale = function () {
  72735. return this._scaleVector.clone();
  72736. };
  72737. /**
  72738. * Copy the scale of the bone to a vector3.
  72739. * @param result The vector3 to copy the scale to
  72740. */
  72741. Bone.prototype.getScaleToRef = function (result) {
  72742. result.copyFrom(this._scaleVector);
  72743. };
  72744. /**
  72745. * Get the position of the bone in local or world space.
  72746. * @param space The space that the returned position is in.
  72747. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72748. * @returns The position of the bone
  72749. */
  72750. Bone.prototype.getPosition = function (space, mesh) {
  72751. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72752. if (mesh === void 0) { mesh = null; }
  72753. var pos = BABYLON.Vector3.Zero();
  72754. this.getPositionToRef(space, mesh, pos);
  72755. return pos;
  72756. };
  72757. /**
  72758. * Copy the position of the bone to a vector3 in local or world space.
  72759. * @param space The space that the returned position is in.
  72760. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72761. * @param result The vector3 to copy the position to.
  72762. */
  72763. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  72764. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72765. if (space == BABYLON.Space.LOCAL) {
  72766. var lm = this.getLocalMatrix();
  72767. result.x = lm.m[12];
  72768. result.y = lm.m[13];
  72769. result.z = lm.m[14];
  72770. }
  72771. else {
  72772. var wm = null;
  72773. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72774. if (mesh) {
  72775. wm = mesh.getWorldMatrix();
  72776. }
  72777. this._skeleton.computeAbsoluteTransforms();
  72778. var tmat = Bone._tmpMats[0];
  72779. if (mesh && wm) {
  72780. tmat.copyFrom(this.getAbsoluteTransform());
  72781. tmat.multiplyToRef(wm, tmat);
  72782. }
  72783. else {
  72784. tmat = this.getAbsoluteTransform();
  72785. }
  72786. result.x = tmat.m[12];
  72787. result.y = tmat.m[13];
  72788. result.z = tmat.m[14];
  72789. }
  72790. };
  72791. /**
  72792. * Get the absolute position of the bone (world space).
  72793. * @param mesh The mesh that this bone is attached to.
  72794. * @returns The absolute position of the bone
  72795. */
  72796. Bone.prototype.getAbsolutePosition = function (mesh) {
  72797. if (mesh === void 0) { mesh = null; }
  72798. var pos = BABYLON.Vector3.Zero();
  72799. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  72800. return pos;
  72801. };
  72802. /**
  72803. * Copy the absolute position of the bone (world space) to the result param.
  72804. * @param mesh The mesh that this bone is attached to.
  72805. * @param result The vector3 to copy the absolute position to.
  72806. */
  72807. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  72808. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  72809. };
  72810. /**
  72811. * Compute the absolute transforms of this bone and its children.
  72812. */
  72813. Bone.prototype.computeAbsoluteTransforms = function () {
  72814. if (this._parent) {
  72815. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72816. }
  72817. else {
  72818. this._absoluteTransform.copyFrom(this._localMatrix);
  72819. var poseMatrix = this._skeleton.getPoseMatrix();
  72820. if (poseMatrix) {
  72821. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  72822. }
  72823. }
  72824. var children = this.children;
  72825. var len = children.length;
  72826. for (var i = 0; i < len; i++) {
  72827. children[i].computeAbsoluteTransforms();
  72828. }
  72829. };
  72830. Bone.prototype._syncScaleVector = function () {
  72831. var lm = this.getLocalMatrix();
  72832. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  72833. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  72834. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  72835. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  72836. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  72837. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  72838. this._scaleVector.x = xs * Math.sqrt(xsq);
  72839. this._scaleVector.y = ys * Math.sqrt(ysq);
  72840. this._scaleVector.z = zs * Math.sqrt(zsq);
  72841. if (this._parent) {
  72842. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  72843. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  72844. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  72845. }
  72846. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  72847. };
  72848. /**
  72849. * Get the world direction from an axis that is in the local space of the bone.
  72850. * @param localAxis The local direction that is used to compute the world direction.
  72851. * @param mesh The mesh that this bone is attached to.
  72852. * @returns The world direction
  72853. */
  72854. Bone.prototype.getDirection = function (localAxis, mesh) {
  72855. if (mesh === void 0) { mesh = null; }
  72856. var result = BABYLON.Vector3.Zero();
  72857. this.getDirectionToRef(localAxis, mesh, result);
  72858. return result;
  72859. };
  72860. /**
  72861. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  72862. * @param localAxis The local direction that is used to compute the world direction.
  72863. * @param mesh The mesh that this bone is attached to.
  72864. * @param result The vector3 that the world direction will be copied to.
  72865. */
  72866. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  72867. if (mesh === void 0) { mesh = null; }
  72868. var wm = null;
  72869. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72870. if (mesh) {
  72871. wm = mesh.getWorldMatrix();
  72872. }
  72873. this._skeleton.computeAbsoluteTransforms();
  72874. var mat = Bone._tmpMats[0];
  72875. mat.copyFrom(this.getAbsoluteTransform());
  72876. if (mesh && wm) {
  72877. mat.multiplyToRef(wm, mat);
  72878. }
  72879. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  72880. result.normalize();
  72881. };
  72882. /**
  72883. * Get the euler rotation of the bone in local or world space.
  72884. * @param space The space that the rotation should be in.
  72885. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72886. * @returns The euler rotation
  72887. */
  72888. Bone.prototype.getRotation = function (space, mesh) {
  72889. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72890. if (mesh === void 0) { mesh = null; }
  72891. var result = BABYLON.Vector3.Zero();
  72892. this.getRotationToRef(space, mesh, result);
  72893. return result;
  72894. };
  72895. /**
  72896. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  72897. * @param space The space that the rotation should be in.
  72898. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72899. * @param result The vector3 that the rotation should be copied to.
  72900. */
  72901. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  72902. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72903. if (mesh === void 0) { mesh = null; }
  72904. var quat = Bone._tmpQuat;
  72905. this.getRotationQuaternionToRef(space, mesh, quat);
  72906. quat.toEulerAnglesToRef(result);
  72907. };
  72908. /**
  72909. * Get the quaternion rotation of the bone in either local or world space.
  72910. * @param space The space that the rotation should be in.
  72911. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72912. * @returns The quaternion rotation
  72913. */
  72914. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  72915. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72916. if (mesh === void 0) { mesh = null; }
  72917. var result = BABYLON.Quaternion.Identity();
  72918. this.getRotationQuaternionToRef(space, mesh, result);
  72919. return result;
  72920. };
  72921. /**
  72922. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  72923. * @param space The space that the rotation should be in.
  72924. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72925. * @param result The quaternion that the rotation should be copied to.
  72926. */
  72927. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  72928. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72929. if (mesh === void 0) { mesh = null; }
  72930. if (space == BABYLON.Space.LOCAL) {
  72931. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72932. }
  72933. else {
  72934. var mat = Bone._tmpMats[0];
  72935. var amat = this.getAbsoluteTransform();
  72936. if (mesh) {
  72937. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72938. }
  72939. else {
  72940. mat.copyFrom(amat);
  72941. }
  72942. mat.m[0] *= this._scalingDeterminant;
  72943. mat.m[1] *= this._scalingDeterminant;
  72944. mat.m[2] *= this._scalingDeterminant;
  72945. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72946. }
  72947. };
  72948. /**
  72949. * Get the rotation matrix of the bone in local or world space.
  72950. * @param space The space that the rotation should be in.
  72951. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72952. * @returns The rotation matrix
  72953. */
  72954. Bone.prototype.getRotationMatrix = function (space, mesh) {
  72955. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72956. var result = BABYLON.Matrix.Identity();
  72957. this.getRotationMatrixToRef(space, mesh, result);
  72958. return result;
  72959. };
  72960. /**
  72961. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  72962. * @param space The space that the rotation should be in.
  72963. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72964. * @param result The quaternion that the rotation should be copied to.
  72965. */
  72966. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  72967. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72968. if (space == BABYLON.Space.LOCAL) {
  72969. this.getLocalMatrix().getRotationMatrixToRef(result);
  72970. }
  72971. else {
  72972. var mat = Bone._tmpMats[0];
  72973. var amat = this.getAbsoluteTransform();
  72974. if (mesh) {
  72975. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72976. }
  72977. else {
  72978. mat.copyFrom(amat);
  72979. }
  72980. mat.m[0] *= this._scalingDeterminant;
  72981. mat.m[1] *= this._scalingDeterminant;
  72982. mat.m[2] *= this._scalingDeterminant;
  72983. mat.getRotationMatrixToRef(result);
  72984. }
  72985. };
  72986. /**
  72987. * Get the world position of a point that is in the local space of the bone.
  72988. * @param position The local position
  72989. * @param mesh The mesh that this bone is attached to.
  72990. * @returns The world position
  72991. */
  72992. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  72993. if (mesh === void 0) { mesh = null; }
  72994. var result = BABYLON.Vector3.Zero();
  72995. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  72996. return result;
  72997. };
  72998. /**
  72999. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  73000. * @param position The local position
  73001. * @param mesh The mesh that this bone is attached to.
  73002. * @param result The vector3 that the world position should be copied to.
  73003. */
  73004. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  73005. if (mesh === void 0) { mesh = null; }
  73006. var wm = null;
  73007. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73008. if (mesh) {
  73009. wm = mesh.getWorldMatrix();
  73010. }
  73011. this._skeleton.computeAbsoluteTransforms();
  73012. var tmat = Bone._tmpMats[0];
  73013. if (mesh && wm) {
  73014. tmat.copyFrom(this.getAbsoluteTransform());
  73015. tmat.multiplyToRef(wm, tmat);
  73016. }
  73017. else {
  73018. tmat = this.getAbsoluteTransform();
  73019. }
  73020. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73021. };
  73022. /**
  73023. * Get the local position of a point that is in world space.
  73024. * @param position The world position
  73025. * @param mesh The mesh that this bone is attached to.
  73026. * @returns The local position
  73027. */
  73028. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  73029. if (mesh === void 0) { mesh = null; }
  73030. var result = BABYLON.Vector3.Zero();
  73031. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  73032. return result;
  73033. };
  73034. /**
  73035. * Get the local position of a point that is in world space and copy it to the result param.
  73036. * @param position The world position
  73037. * @param mesh The mesh that this bone is attached to.
  73038. * @param result The vector3 that the local position should be copied to.
  73039. */
  73040. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  73041. if (mesh === void 0) { mesh = null; }
  73042. var wm = null;
  73043. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73044. if (mesh) {
  73045. wm = mesh.getWorldMatrix();
  73046. }
  73047. this._skeleton.computeAbsoluteTransforms();
  73048. var tmat = Bone._tmpMats[0];
  73049. tmat.copyFrom(this.getAbsoluteTransform());
  73050. if (mesh && wm) {
  73051. tmat.multiplyToRef(wm, tmat);
  73052. }
  73053. tmat.invert();
  73054. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73055. };
  73056. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73057. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  73058. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73059. return Bone;
  73060. }(BABYLON.Node));
  73061. BABYLON.Bone = Bone;
  73062. })(BABYLON || (BABYLON = {}));
  73063. //# sourceMappingURL=babylon.bone.js.map
  73064. "use strict";
  73065. var BABYLON;
  73066. (function (BABYLON) {
  73067. var BoneIKController = /** @class */ (function () {
  73068. function BoneIKController(mesh, bone, options) {
  73069. this.targetPosition = BABYLON.Vector3.Zero();
  73070. this.poleTargetPosition = BABYLON.Vector3.Zero();
  73071. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  73072. this.poleAngle = 0;
  73073. this.slerpAmount = 1;
  73074. this._bone1Quat = BABYLON.Quaternion.Identity();
  73075. this._bone1Mat = BABYLON.Matrix.Identity();
  73076. this._bone2Ang = Math.PI;
  73077. this._maxAngle = Math.PI;
  73078. this._rightHandedSystem = false;
  73079. this._bendAxis = BABYLON.Vector3.Right();
  73080. this._slerping = false;
  73081. this._adjustRoll = 0;
  73082. this._bone2 = bone;
  73083. this._bone1 = bone.getParent();
  73084. if (!this._bone1) {
  73085. return;
  73086. }
  73087. this.mesh = mesh;
  73088. var bonePos = bone.getPosition();
  73089. if (bone.getAbsoluteTransform().determinant() > 0) {
  73090. this._rightHandedSystem = true;
  73091. this._bendAxis.x = 0;
  73092. this._bendAxis.y = 0;
  73093. this._bendAxis.z = -1;
  73094. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  73095. this._adjustRoll = Math.PI * .5;
  73096. this._bendAxis.z = 1;
  73097. }
  73098. }
  73099. if (this._bone1.length) {
  73100. var boneScale1 = this._bone1.getScale();
  73101. var boneScale2 = this._bone2.getScale();
  73102. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  73103. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  73104. }
  73105. else if (this._bone1.children[0]) {
  73106. mesh.computeWorldMatrix(true);
  73107. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  73108. var pos2 = this._bone2.getAbsolutePosition(mesh);
  73109. var pos3 = this._bone1.getAbsolutePosition(mesh);
  73110. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  73111. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  73112. }
  73113. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  73114. this.maxAngle = Math.PI;
  73115. if (options) {
  73116. if (options.targetMesh) {
  73117. this.targetMesh = options.targetMesh;
  73118. this.targetMesh.computeWorldMatrix(true);
  73119. }
  73120. if (options.poleTargetMesh) {
  73121. this.poleTargetMesh = options.poleTargetMesh;
  73122. this.poleTargetMesh.computeWorldMatrix(true);
  73123. }
  73124. else if (options.poleTargetBone) {
  73125. this.poleTargetBone = options.poleTargetBone;
  73126. }
  73127. else if (this._bone1.getParent()) {
  73128. this.poleTargetBone = this._bone1.getParent();
  73129. }
  73130. if (options.poleTargetLocalOffset) {
  73131. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  73132. }
  73133. if (options.poleAngle) {
  73134. this.poleAngle = options.poleAngle;
  73135. }
  73136. if (options.bendAxis) {
  73137. this._bendAxis.copyFrom(options.bendAxis);
  73138. }
  73139. if (options.maxAngle) {
  73140. this.maxAngle = options.maxAngle;
  73141. }
  73142. if (options.slerpAmount) {
  73143. this.slerpAmount = options.slerpAmount;
  73144. }
  73145. }
  73146. }
  73147. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  73148. get: function () {
  73149. return this._maxAngle;
  73150. },
  73151. set: function (value) {
  73152. this._setMaxAngle(value);
  73153. },
  73154. enumerable: true,
  73155. configurable: true
  73156. });
  73157. BoneIKController.prototype._setMaxAngle = function (ang) {
  73158. if (ang < 0) {
  73159. ang = 0;
  73160. }
  73161. if (ang > Math.PI || ang == undefined) {
  73162. ang = Math.PI;
  73163. }
  73164. this._maxAngle = ang;
  73165. var a = this._bone1Length;
  73166. var b = this._bone2Length;
  73167. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  73168. };
  73169. BoneIKController.prototype.update = function () {
  73170. var bone1 = this._bone1;
  73171. if (!bone1) {
  73172. return;
  73173. }
  73174. var target = this.targetPosition;
  73175. var poleTarget = this.poleTargetPosition;
  73176. var mat1 = BoneIKController._tmpMats[0];
  73177. var mat2 = BoneIKController._tmpMats[1];
  73178. if (this.targetMesh) {
  73179. target.copyFrom(this.targetMesh.getAbsolutePosition());
  73180. }
  73181. if (this.poleTargetBone) {
  73182. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  73183. }
  73184. else if (this.poleTargetMesh) {
  73185. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  73186. }
  73187. var bonePos = BoneIKController._tmpVecs[0];
  73188. var zaxis = BoneIKController._tmpVecs[1];
  73189. var xaxis = BoneIKController._tmpVecs[2];
  73190. var yaxis = BoneIKController._tmpVecs[3];
  73191. var upAxis = BoneIKController._tmpVecs[4];
  73192. var _tmpQuat = BoneIKController._tmpQuat;
  73193. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  73194. poleTarget.subtractToRef(bonePos, upAxis);
  73195. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  73196. upAxis.y = 1;
  73197. }
  73198. else {
  73199. upAxis.normalize();
  73200. }
  73201. target.subtractToRef(bonePos, yaxis);
  73202. yaxis.normalize();
  73203. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  73204. zaxis.normalize();
  73205. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  73206. xaxis.normalize();
  73207. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  73208. var a = this._bone1Length;
  73209. var b = this._bone2Length;
  73210. var c = BABYLON.Vector3.Distance(bonePos, target);
  73211. if (this._maxReach > 0) {
  73212. c = Math.min(this._maxReach, c);
  73213. }
  73214. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  73215. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  73216. if (acosa > 1) {
  73217. acosa = 1;
  73218. }
  73219. if (acosb > 1) {
  73220. acosb = 1;
  73221. }
  73222. if (acosa < -1) {
  73223. acosa = -1;
  73224. }
  73225. if (acosb < -1) {
  73226. acosb = -1;
  73227. }
  73228. var angA = Math.acos(acosa);
  73229. var angB = Math.acos(acosb);
  73230. var angC = -angA - angB;
  73231. if (this._rightHandedSystem) {
  73232. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  73233. mat2.multiplyToRef(mat1, mat1);
  73234. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  73235. mat2.multiplyToRef(mat1, mat1);
  73236. }
  73237. else {
  73238. var _tmpVec = BoneIKController._tmpVecs[5];
  73239. _tmpVec.copyFrom(this._bendAxis);
  73240. _tmpVec.x *= -1;
  73241. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  73242. mat2.multiplyToRef(mat1, mat1);
  73243. }
  73244. if (this.poleAngle) {
  73245. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  73246. mat1.multiplyToRef(mat2, mat1);
  73247. }
  73248. if (this._bone1) {
  73249. if (this.slerpAmount < 1) {
  73250. if (!this._slerping) {
  73251. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  73252. }
  73253. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  73254. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  73255. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  73256. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  73257. this._slerping = true;
  73258. }
  73259. else {
  73260. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  73261. this._bone1Mat.copyFrom(mat1);
  73262. this._slerping = false;
  73263. }
  73264. }
  73265. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  73266. this._bone2Ang = angC;
  73267. };
  73268. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73269. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  73270. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73271. return BoneIKController;
  73272. }());
  73273. BABYLON.BoneIKController = BoneIKController;
  73274. })(BABYLON || (BABYLON = {}));
  73275. //# sourceMappingURL=babylon.boneIKController.js.map
  73276. "use strict";
  73277. var BABYLON;
  73278. (function (BABYLON) {
  73279. var BoneLookController = /** @class */ (function () {
  73280. /**
  73281. * Create a BoneLookController
  73282. * @param mesh the mesh that the bone belongs to
  73283. * @param bone the bone that will be looking to the target
  73284. * @param target the target Vector3 to look at
  73285. * @param settings optional settings:
  73286. * - maxYaw: the maximum angle the bone will yaw to
  73287. * - minYaw: the minimum angle the bone will yaw to
  73288. * - maxPitch: the maximum angle the bone will pitch to
  73289. * - minPitch: the minimum angle the bone will yaw to
  73290. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  73291. * - upAxis: the up axis of the coordinate system
  73292. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73293. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  73294. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  73295. * - adjustYaw: used to make an adjustment to the yaw of the bone
  73296. * - adjustPitch: used to make an adjustment to the pitch of the bone
  73297. * - adjustRoll: used to make an adjustment to the roll of the bone
  73298. **/
  73299. function BoneLookController(mesh, bone, target, options) {
  73300. /**
  73301. * The up axis of the coordinate system that is used when the bone is rotated.
  73302. */
  73303. this.upAxis = BABYLON.Vector3.Up();
  73304. /**
  73305. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73306. */
  73307. this.upAxisSpace = BABYLON.Space.LOCAL;
  73308. /**
  73309. * Used to make an adjustment to the yaw of the bone.
  73310. */
  73311. this.adjustYaw = 0;
  73312. /**
  73313. * Used to make an adjustment to the pitch of the bone.
  73314. */
  73315. this.adjustPitch = 0;
  73316. /**
  73317. * Used to make an adjustment to the roll of the bone.
  73318. */
  73319. this.adjustRoll = 0;
  73320. /**
  73321. * 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).
  73322. */
  73323. this.slerpAmount = 1;
  73324. this._boneQuat = BABYLON.Quaternion.Identity();
  73325. this._slerping = false;
  73326. this._firstFrameSkipped = false;
  73327. this._fowardAxis = BABYLON.Vector3.Forward();
  73328. this.mesh = mesh;
  73329. this.bone = bone;
  73330. this.target = target;
  73331. if (options) {
  73332. if (options.adjustYaw) {
  73333. this.adjustYaw = options.adjustYaw;
  73334. }
  73335. if (options.adjustPitch) {
  73336. this.adjustPitch = options.adjustPitch;
  73337. }
  73338. if (options.adjustRoll) {
  73339. this.adjustRoll = options.adjustRoll;
  73340. }
  73341. if (options.maxYaw != null) {
  73342. this.maxYaw = options.maxYaw;
  73343. }
  73344. else {
  73345. this.maxYaw = Math.PI;
  73346. }
  73347. if (options.minYaw != null) {
  73348. this.minYaw = options.minYaw;
  73349. }
  73350. else {
  73351. this.minYaw = -Math.PI;
  73352. }
  73353. if (options.maxPitch != null) {
  73354. this.maxPitch = options.maxPitch;
  73355. }
  73356. else {
  73357. this.maxPitch = Math.PI;
  73358. }
  73359. if (options.minPitch != null) {
  73360. this.minPitch = options.minPitch;
  73361. }
  73362. else {
  73363. this.minPitch = -Math.PI;
  73364. }
  73365. if (options.slerpAmount != null) {
  73366. this.slerpAmount = options.slerpAmount;
  73367. }
  73368. if (options.upAxis != null) {
  73369. this.upAxis = options.upAxis;
  73370. }
  73371. if (options.upAxisSpace != null) {
  73372. this.upAxisSpace = options.upAxisSpace;
  73373. }
  73374. if (options.yawAxis != null || options.pitchAxis != null) {
  73375. var newYawAxis = BABYLON.Axis.Y;
  73376. var newPitchAxis = BABYLON.Axis.X;
  73377. if (options.yawAxis != null) {
  73378. newYawAxis = options.yawAxis.clone();
  73379. newYawAxis.normalize();
  73380. }
  73381. if (options.pitchAxis != null) {
  73382. newPitchAxis = options.pitchAxis.clone();
  73383. newPitchAxis.normalize();
  73384. }
  73385. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  73386. this._transformYawPitch = BABYLON.Matrix.Identity();
  73387. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  73388. this._transformYawPitchInv = this._transformYawPitch.clone();
  73389. this._transformYawPitch.invert();
  73390. }
  73391. }
  73392. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  73393. this.upAxisSpace = BABYLON.Space.LOCAL;
  73394. }
  73395. }
  73396. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  73397. /**
  73398. * Get/set the minimum yaw angle that the bone can look to.
  73399. */
  73400. get: function () {
  73401. return this._minYaw;
  73402. },
  73403. set: function (value) {
  73404. this._minYaw = value;
  73405. this._minYawSin = Math.sin(value);
  73406. this._minYawCos = Math.cos(value);
  73407. if (this._maxYaw != null) {
  73408. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73409. this._yawRange = this._maxYaw - this._minYaw;
  73410. }
  73411. },
  73412. enumerable: true,
  73413. configurable: true
  73414. });
  73415. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  73416. /**
  73417. * Get/set the maximum yaw angle that the bone can look to.
  73418. */
  73419. get: function () {
  73420. return this._maxYaw;
  73421. },
  73422. set: function (value) {
  73423. this._maxYaw = value;
  73424. this._maxYawSin = Math.sin(value);
  73425. this._maxYawCos = Math.cos(value);
  73426. if (this._minYaw != null) {
  73427. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73428. this._yawRange = this._maxYaw - this._minYaw;
  73429. }
  73430. },
  73431. enumerable: true,
  73432. configurable: true
  73433. });
  73434. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  73435. /**
  73436. * Get/set the minimum pitch angle that the bone can look to.
  73437. */
  73438. get: function () {
  73439. return this._minPitch;
  73440. },
  73441. set: function (value) {
  73442. this._minPitch = value;
  73443. this._minPitchTan = Math.tan(value);
  73444. },
  73445. enumerable: true,
  73446. configurable: true
  73447. });
  73448. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  73449. /**
  73450. * Get/set the maximum pitch angle that the bone can look to.
  73451. */
  73452. get: function () {
  73453. return this._maxPitch;
  73454. },
  73455. set: function (value) {
  73456. this._maxPitch = value;
  73457. this._maxPitchTan = Math.tan(value);
  73458. },
  73459. enumerable: true,
  73460. configurable: true
  73461. });
  73462. /**
  73463. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  73464. */
  73465. BoneLookController.prototype.update = function () {
  73466. //skip the first frame when slerping so that the mesh rotation is correct
  73467. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  73468. this._firstFrameSkipped = true;
  73469. return;
  73470. }
  73471. var bone = this.bone;
  73472. var bonePos = BoneLookController._tmpVecs[0];
  73473. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  73474. var target = this.target;
  73475. var _tmpMat1 = BoneLookController._tmpMats[0];
  73476. var _tmpMat2 = BoneLookController._tmpMats[1];
  73477. var mesh = this.mesh;
  73478. var parentBone = bone.getParent();
  73479. var upAxis = BoneLookController._tmpVecs[1];
  73480. upAxis.copyFrom(this.upAxis);
  73481. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  73482. if (this._transformYawPitch) {
  73483. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  73484. }
  73485. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  73486. }
  73487. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  73488. mesh.getDirectionToRef(upAxis, upAxis);
  73489. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  73490. upAxis.normalize();
  73491. }
  73492. }
  73493. var checkYaw = false;
  73494. var checkPitch = false;
  73495. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  73496. checkYaw = true;
  73497. }
  73498. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  73499. checkPitch = true;
  73500. }
  73501. if (checkYaw || checkPitch) {
  73502. var spaceMat = BoneLookController._tmpMats[2];
  73503. var spaceMatInv = BoneLookController._tmpMats[3];
  73504. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  73505. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  73506. }
  73507. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  73508. spaceMat.copyFrom(mesh.getWorldMatrix());
  73509. }
  73510. else {
  73511. var forwardAxis = BoneLookController._tmpVecs[2];
  73512. forwardAxis.copyFrom(this._fowardAxis);
  73513. if (this._transformYawPitch) {
  73514. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  73515. }
  73516. if (parentBone) {
  73517. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  73518. }
  73519. else {
  73520. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  73521. }
  73522. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  73523. rightAxis.normalize();
  73524. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  73525. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  73526. }
  73527. spaceMat.invertToRef(spaceMatInv);
  73528. var xzlen = null;
  73529. if (checkPitch) {
  73530. var localTarget = BoneLookController._tmpVecs[3];
  73531. target.subtractToRef(bonePos, localTarget);
  73532. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73533. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73534. var pitch = Math.atan2(localTarget.y, xzlen);
  73535. var newPitch = pitch;
  73536. if (pitch > this._maxPitch) {
  73537. localTarget.y = this._maxPitchTan * xzlen;
  73538. newPitch = this._maxPitch;
  73539. }
  73540. else if (pitch < this._minPitch) {
  73541. localTarget.y = this._minPitchTan * xzlen;
  73542. newPitch = this._minPitch;
  73543. }
  73544. if (pitch != newPitch) {
  73545. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73546. localTarget.addInPlace(bonePos);
  73547. target = localTarget;
  73548. }
  73549. }
  73550. if (checkYaw) {
  73551. var localTarget = BoneLookController._tmpVecs[4];
  73552. target.subtractToRef(bonePos, localTarget);
  73553. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73554. var yaw = Math.atan2(localTarget.x, localTarget.z);
  73555. var newYaw = yaw;
  73556. if (yaw > this._maxYaw || yaw < this._minYaw) {
  73557. if (xzlen == null) {
  73558. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73559. }
  73560. if (this._yawRange > Math.PI) {
  73561. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  73562. localTarget.z = this._maxYawCos * xzlen;
  73563. localTarget.x = this._maxYawSin * xzlen;
  73564. newYaw = this._maxYaw;
  73565. }
  73566. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  73567. localTarget.z = this._minYawCos * xzlen;
  73568. localTarget.x = this._minYawSin * xzlen;
  73569. newYaw = this._minYaw;
  73570. }
  73571. }
  73572. else {
  73573. if (yaw > this._maxYaw) {
  73574. localTarget.z = this._maxYawCos * xzlen;
  73575. localTarget.x = this._maxYawSin * xzlen;
  73576. newYaw = this._maxYaw;
  73577. }
  73578. else if (yaw < this._minYaw) {
  73579. localTarget.z = this._minYawCos * xzlen;
  73580. localTarget.x = this._minYawSin * xzlen;
  73581. newYaw = this._minYaw;
  73582. }
  73583. }
  73584. }
  73585. if (this._slerping && this._yawRange > Math.PI) {
  73586. //are we going to be crossing into the min/max region?
  73587. var boneFwd = BoneLookController._tmpVecs[8];
  73588. boneFwd.copyFrom(BABYLON.Axis.Z);
  73589. if (this._transformYawPitch) {
  73590. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  73591. }
  73592. var boneRotMat = BoneLookController._tmpMats[4];
  73593. this._boneQuat.toRotationMatrix(boneRotMat);
  73594. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  73595. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  73596. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  73597. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  73598. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  73599. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  73600. if (angBtwTar > angBtwMidYaw) {
  73601. if (xzlen == null) {
  73602. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73603. }
  73604. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  73605. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  73606. if (angBtwMin < angBtwMax) {
  73607. newYaw = boneYaw + Math.PI * .75;
  73608. localTarget.z = Math.cos(newYaw) * xzlen;
  73609. localTarget.x = Math.sin(newYaw) * xzlen;
  73610. }
  73611. else {
  73612. newYaw = boneYaw - Math.PI * .75;
  73613. localTarget.z = Math.cos(newYaw) * xzlen;
  73614. localTarget.x = Math.sin(newYaw) * xzlen;
  73615. }
  73616. }
  73617. }
  73618. if (yaw != newYaw) {
  73619. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73620. localTarget.addInPlace(bonePos);
  73621. target = localTarget;
  73622. }
  73623. }
  73624. }
  73625. var zaxis = BoneLookController._tmpVecs[5];
  73626. var xaxis = BoneLookController._tmpVecs[6];
  73627. var yaxis = BoneLookController._tmpVecs[7];
  73628. var _tmpQuat = BoneLookController._tmpQuat;
  73629. target.subtractToRef(bonePos, zaxis);
  73630. zaxis.normalize();
  73631. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  73632. xaxis.normalize();
  73633. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  73634. yaxis.normalize();
  73635. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  73636. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  73637. return;
  73638. }
  73639. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  73640. return;
  73641. }
  73642. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  73643. return;
  73644. }
  73645. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  73646. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  73647. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  73648. }
  73649. if (this.slerpAmount < 1) {
  73650. if (!this._slerping) {
  73651. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  73652. }
  73653. if (this._transformYawPitch) {
  73654. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  73655. }
  73656. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  73657. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  73658. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  73659. this._slerping = true;
  73660. }
  73661. else {
  73662. if (this._transformYawPitch) {
  73663. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  73664. }
  73665. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  73666. this._slerping = false;
  73667. }
  73668. };
  73669. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  73670. var angDiff = ang2 - ang1;
  73671. angDiff %= Math.PI * 2;
  73672. if (angDiff > Math.PI) {
  73673. angDiff -= Math.PI * 2;
  73674. }
  73675. else if (angDiff < -Math.PI) {
  73676. angDiff += Math.PI * 2;
  73677. }
  73678. return angDiff;
  73679. };
  73680. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  73681. ang1 %= (2 * Math.PI);
  73682. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  73683. ang2 %= (2 * Math.PI);
  73684. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  73685. var ab = 0;
  73686. if (ang1 < ang2) {
  73687. ab = ang2 - ang1;
  73688. }
  73689. else {
  73690. ab = ang1 - ang2;
  73691. }
  73692. if (ab > Math.PI) {
  73693. ab = Math.PI * 2 - ab;
  73694. }
  73695. return ab;
  73696. };
  73697. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  73698. ang %= (2 * Math.PI);
  73699. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  73700. ang1 %= (2 * Math.PI);
  73701. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  73702. ang2 %= (2 * Math.PI);
  73703. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  73704. if (ang1 < ang2) {
  73705. if (ang > ang1 && ang < ang2) {
  73706. return true;
  73707. }
  73708. }
  73709. else {
  73710. if (ang > ang2 && ang < ang1) {
  73711. return true;
  73712. }
  73713. }
  73714. return false;
  73715. };
  73716. 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()];
  73717. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  73718. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73719. return BoneLookController;
  73720. }());
  73721. BABYLON.BoneLookController = BoneLookController;
  73722. })(BABYLON || (BABYLON = {}));
  73723. //# sourceMappingURL=babylon.boneLookController.js.map
  73724. "use strict";
  73725. var BABYLON;
  73726. (function (BABYLON) {
  73727. var Skeleton = /** @class */ (function () {
  73728. function Skeleton(name, id, scene) {
  73729. this.name = name;
  73730. this.id = id;
  73731. this.bones = new Array();
  73732. this.needInitialSkinMatrix = false;
  73733. this._isDirty = true;
  73734. this._meshesWithPoseMatrix = new Array();
  73735. this._identity = BABYLON.Matrix.Identity();
  73736. this._ranges = {};
  73737. this._lastAbsoluteTransformsUpdateId = -1;
  73738. /**
  73739. * Specifies if the skeleton should be serialized.
  73740. */
  73741. this.doNotSerialize = false;
  73742. // Events
  73743. /**
  73744. * An event triggered before computing the skeleton's matrices
  73745. * @type {BABYLON.Observable}
  73746. */
  73747. this.onBeforeComputeObservable = new BABYLON.Observable();
  73748. this.bones = [];
  73749. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73750. scene.skeletons.push(this);
  73751. //make sure it will recalculate the matrix next time prepare is called.
  73752. this._isDirty = true;
  73753. }
  73754. // Members
  73755. Skeleton.prototype.getTransformMatrices = function (mesh) {
  73756. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  73757. return mesh._bonesTransformMatrices;
  73758. }
  73759. if (!this._transformMatrices) {
  73760. this.prepare();
  73761. }
  73762. return this._transformMatrices;
  73763. };
  73764. Skeleton.prototype.getScene = function () {
  73765. return this._scene;
  73766. };
  73767. // Methods
  73768. /**
  73769. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  73770. */
  73771. Skeleton.prototype.toString = function (fullDetails) {
  73772. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  73773. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  73774. if (fullDetails) {
  73775. ret += ", Ranges: {";
  73776. var first = true;
  73777. for (var name_1 in this._ranges) {
  73778. if (first) {
  73779. ret += ", ";
  73780. first = false;
  73781. }
  73782. ret += name_1;
  73783. }
  73784. ret += "}";
  73785. }
  73786. return ret;
  73787. };
  73788. /**
  73789. * Get bone's index searching by name
  73790. * @param {string} name is bone's name to search for
  73791. * @return {number} Indice of the bone. Returns -1 if not found
  73792. */
  73793. Skeleton.prototype.getBoneIndexByName = function (name) {
  73794. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  73795. if (this.bones[boneIndex].name === name) {
  73796. return boneIndex;
  73797. }
  73798. }
  73799. return -1;
  73800. };
  73801. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  73802. // check name not already in use
  73803. if (!this._ranges[name]) {
  73804. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  73805. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73806. if (this.bones[i].animations[0]) {
  73807. this.bones[i].animations[0].createRange(name, from, to);
  73808. }
  73809. }
  73810. }
  73811. };
  73812. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  73813. if (deleteFrames === void 0) { deleteFrames = true; }
  73814. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73815. if (this.bones[i].animations[0]) {
  73816. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  73817. }
  73818. }
  73819. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  73820. };
  73821. Skeleton.prototype.getAnimationRange = function (name) {
  73822. return this._ranges[name];
  73823. };
  73824. /**
  73825. * Returns as an Array, all AnimationRanges defined on this skeleton
  73826. */
  73827. Skeleton.prototype.getAnimationRanges = function () {
  73828. var animationRanges = [];
  73829. var name;
  73830. var i = 0;
  73831. for (name in this._ranges) {
  73832. animationRanges[i] = this._ranges[name];
  73833. i++;
  73834. }
  73835. return animationRanges;
  73836. };
  73837. /**
  73838. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  73839. */
  73840. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  73841. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  73842. if (this._ranges[name] || !source.getAnimationRange(name)) {
  73843. return false;
  73844. }
  73845. var ret = true;
  73846. var frameOffset = this._getHighestAnimationFrame() + 1;
  73847. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  73848. var boneDict = {};
  73849. var sourceBones = source.bones;
  73850. var nBones;
  73851. var i;
  73852. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  73853. boneDict[sourceBones[i].name] = sourceBones[i];
  73854. }
  73855. if (this.bones.length !== sourceBones.length) {
  73856. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  73857. ret = false;
  73858. }
  73859. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  73860. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  73861. var boneName = this.bones[i].name;
  73862. var sourceBone = boneDict[boneName];
  73863. if (sourceBone) {
  73864. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  73865. }
  73866. else {
  73867. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  73868. ret = false;
  73869. }
  73870. }
  73871. // do not call createAnimationRange(), since it also is done to bones, which was already done
  73872. var range = source.getAnimationRange(name);
  73873. if (range) {
  73874. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  73875. }
  73876. return ret;
  73877. };
  73878. Skeleton.prototype.returnToRest = function () {
  73879. for (var index = 0; index < this.bones.length; index++) {
  73880. this.bones[index].returnToRest();
  73881. }
  73882. };
  73883. Skeleton.prototype._getHighestAnimationFrame = function () {
  73884. var ret = 0;
  73885. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73886. if (this.bones[i].animations[0]) {
  73887. var highest = this.bones[i].animations[0].getHighestFrame();
  73888. if (ret < highest) {
  73889. ret = highest;
  73890. }
  73891. }
  73892. }
  73893. return ret;
  73894. };
  73895. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  73896. var range = this.getAnimationRange(name);
  73897. if (!range) {
  73898. return null;
  73899. }
  73900. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  73901. };
  73902. Skeleton.prototype._markAsDirty = function () {
  73903. this._isDirty = true;
  73904. };
  73905. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  73906. this._meshesWithPoseMatrix.push(mesh);
  73907. };
  73908. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  73909. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  73910. if (index > -1) {
  73911. this._meshesWithPoseMatrix.splice(index, 1);
  73912. }
  73913. };
  73914. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  73915. this.onBeforeComputeObservable.notifyObservers(this);
  73916. for (var index = 0; index < this.bones.length; index++) {
  73917. var bone = this.bones[index];
  73918. var parentBone = bone.getParent();
  73919. if (parentBone) {
  73920. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  73921. }
  73922. else {
  73923. if (initialSkinMatrix) {
  73924. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  73925. }
  73926. else {
  73927. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  73928. }
  73929. }
  73930. if (bone._index !== -1) {
  73931. var mappedIndex = bone._index === null ? index : bone._index;
  73932. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  73933. }
  73934. }
  73935. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  73936. };
  73937. Skeleton.prototype.prepare = function () {
  73938. if (!this._isDirty) {
  73939. return;
  73940. }
  73941. if (this.needInitialSkinMatrix) {
  73942. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  73943. var mesh = this._meshesWithPoseMatrix[index];
  73944. var poseMatrix = mesh.getPoseMatrix();
  73945. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  73946. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73947. }
  73948. if (this._synchronizedWithMesh !== mesh) {
  73949. this._synchronizedWithMesh = mesh;
  73950. // Prepare bones
  73951. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  73952. var bone = this.bones[boneIndex];
  73953. if (!bone.getParent()) {
  73954. var matrix = bone.getBaseMatrix();
  73955. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  73956. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  73957. }
  73958. }
  73959. }
  73960. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  73961. }
  73962. }
  73963. else {
  73964. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  73965. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73966. }
  73967. this._computeTransformMatrices(this._transformMatrices, null);
  73968. }
  73969. this._isDirty = false;
  73970. this._scene._activeBones.addCount(this.bones.length, false);
  73971. };
  73972. Skeleton.prototype.getAnimatables = function () {
  73973. if (!this._animatables || this._animatables.length !== this.bones.length) {
  73974. this._animatables = [];
  73975. for (var index = 0; index < this.bones.length; index++) {
  73976. this._animatables.push(this.bones[index]);
  73977. }
  73978. }
  73979. return this._animatables;
  73980. };
  73981. Skeleton.prototype.clone = function (name, id) {
  73982. var result = new Skeleton(name, id || name, this._scene);
  73983. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  73984. for (var index = 0; index < this.bones.length; index++) {
  73985. var source = this.bones[index];
  73986. var parentBone = null;
  73987. var parent_1 = source.getParent();
  73988. if (parent_1) {
  73989. var parentIndex = this.bones.indexOf(parent_1);
  73990. parentBone = result.bones[parentIndex];
  73991. }
  73992. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  73993. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  73994. }
  73995. if (this._ranges) {
  73996. result._ranges = {};
  73997. for (var rangeName in this._ranges) {
  73998. var range = this._ranges[rangeName];
  73999. if (range) {
  74000. result._ranges[rangeName] = range.clone();
  74001. }
  74002. }
  74003. }
  74004. this._isDirty = true;
  74005. return result;
  74006. };
  74007. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  74008. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  74009. this.bones.forEach(function (bone) {
  74010. bone.animations.forEach(function (animation) {
  74011. animation.enableBlending = true;
  74012. animation.blendingSpeed = blendingSpeed;
  74013. });
  74014. });
  74015. };
  74016. Skeleton.prototype.dispose = function () {
  74017. this._meshesWithPoseMatrix = [];
  74018. // Animations
  74019. this.getScene().stopAnimation(this);
  74020. // Remove from scene
  74021. this.getScene().removeSkeleton(this);
  74022. };
  74023. Skeleton.prototype.serialize = function () {
  74024. var serializationObject = {};
  74025. serializationObject.name = this.name;
  74026. serializationObject.id = this.id;
  74027. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  74028. serializationObject.bones = [];
  74029. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74030. for (var index = 0; index < this.bones.length; index++) {
  74031. var bone = this.bones[index];
  74032. var parent_2 = bone.getParent();
  74033. var serializedBone = {
  74034. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  74035. name: bone.name,
  74036. matrix: bone.getBaseMatrix().toArray(),
  74037. rest: bone.getRestPose().toArray()
  74038. };
  74039. serializationObject.bones.push(serializedBone);
  74040. if (bone.length) {
  74041. serializedBone.length = bone.length;
  74042. }
  74043. if (bone.animations && bone.animations.length > 0) {
  74044. serializedBone.animation = bone.animations[0].serialize();
  74045. }
  74046. serializationObject.ranges = [];
  74047. for (var name in this._ranges) {
  74048. var source = this._ranges[name];
  74049. if (!source) {
  74050. continue;
  74051. }
  74052. var range = {};
  74053. range.name = name;
  74054. range.from = source.from;
  74055. range.to = source.to;
  74056. serializationObject.ranges.push(range);
  74057. }
  74058. }
  74059. return serializationObject;
  74060. };
  74061. Skeleton.Parse = function (parsedSkeleton, scene) {
  74062. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  74063. if (parsedSkeleton.dimensionsAtRest) {
  74064. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  74065. }
  74066. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  74067. var index;
  74068. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  74069. var parsedBone = parsedSkeleton.bones[index];
  74070. var parentBone = null;
  74071. if (parsedBone.parentBoneIndex > -1) {
  74072. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  74073. }
  74074. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  74075. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  74076. if (parsedBone.length) {
  74077. bone.length = parsedBone.length;
  74078. }
  74079. if (parsedBone.animation) {
  74080. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  74081. }
  74082. }
  74083. // placed after bones, so createAnimationRange can cascade down
  74084. if (parsedSkeleton.ranges) {
  74085. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  74086. var data = parsedSkeleton.ranges[index];
  74087. skeleton.createAnimationRange(data.name, data.from, data.to);
  74088. }
  74089. }
  74090. return skeleton;
  74091. };
  74092. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  74093. if (forceUpdate === void 0) { forceUpdate = false; }
  74094. var renderId = this._scene.getRenderId();
  74095. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  74096. this.bones[0].computeAbsoluteTransforms();
  74097. this._lastAbsoluteTransformsUpdateId = renderId;
  74098. }
  74099. };
  74100. Skeleton.prototype.getPoseMatrix = function () {
  74101. var poseMatrix = null;
  74102. if (this._meshesWithPoseMatrix.length > 0) {
  74103. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  74104. }
  74105. return poseMatrix;
  74106. };
  74107. Skeleton.prototype.sortBones = function () {
  74108. var bones = new Array();
  74109. var visited = new Array(this.bones.length);
  74110. for (var index = 0; index < this.bones.length; index++) {
  74111. this._sortBones(index, bones, visited);
  74112. }
  74113. this.bones = bones;
  74114. };
  74115. Skeleton.prototype._sortBones = function (index, bones, visited) {
  74116. if (visited[index]) {
  74117. return;
  74118. }
  74119. visited[index] = true;
  74120. var bone = this.bones[index];
  74121. if (bone._index === undefined) {
  74122. bone._index = index;
  74123. }
  74124. var parentBone = bone.getParent();
  74125. if (parentBone) {
  74126. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  74127. }
  74128. bones.push(bone);
  74129. };
  74130. return Skeleton;
  74131. }());
  74132. BABYLON.Skeleton = Skeleton;
  74133. })(BABYLON || (BABYLON = {}));
  74134. //# sourceMappingURL=babylon.skeleton.js.map
  74135. "use strict";
  74136. var BABYLON;
  74137. (function (BABYLON) {
  74138. var SphericalPolynomial = /** @class */ (function () {
  74139. function SphericalPolynomial() {
  74140. this.x = BABYLON.Vector3.Zero();
  74141. this.y = BABYLON.Vector3.Zero();
  74142. this.z = BABYLON.Vector3.Zero();
  74143. this.xx = BABYLON.Vector3.Zero();
  74144. this.yy = BABYLON.Vector3.Zero();
  74145. this.zz = BABYLON.Vector3.Zero();
  74146. this.xy = BABYLON.Vector3.Zero();
  74147. this.yz = BABYLON.Vector3.Zero();
  74148. this.zx = BABYLON.Vector3.Zero();
  74149. }
  74150. SphericalPolynomial.prototype.addAmbient = function (color) {
  74151. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74152. this.xx = this.xx.add(colorVector);
  74153. this.yy = this.yy.add(colorVector);
  74154. this.zz = this.zz.add(colorVector);
  74155. };
  74156. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  74157. var result = new SphericalPolynomial();
  74158. result.x = harmonics.L11.scale(1.02333);
  74159. result.y = harmonics.L1_1.scale(1.02333);
  74160. result.z = harmonics.L10.scale(1.02333);
  74161. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  74162. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  74163. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  74164. result.yz = harmonics.L2_1.scale(0.858086);
  74165. result.zx = harmonics.L21.scale(0.858086);
  74166. result.xy = harmonics.L2_2.scale(0.858086);
  74167. result.scale(1.0 / Math.PI);
  74168. return result;
  74169. };
  74170. SphericalPolynomial.prototype.scale = function (scale) {
  74171. this.x = this.x.scale(scale);
  74172. this.y = this.y.scale(scale);
  74173. this.z = this.z.scale(scale);
  74174. this.xx = this.xx.scale(scale);
  74175. this.yy = this.yy.scale(scale);
  74176. this.zz = this.zz.scale(scale);
  74177. this.yz = this.yz.scale(scale);
  74178. this.zx = this.zx.scale(scale);
  74179. this.xy = this.xy.scale(scale);
  74180. };
  74181. return SphericalPolynomial;
  74182. }());
  74183. BABYLON.SphericalPolynomial = SphericalPolynomial;
  74184. var SphericalHarmonics = /** @class */ (function () {
  74185. function SphericalHarmonics() {
  74186. this.L00 = BABYLON.Vector3.Zero();
  74187. this.L1_1 = BABYLON.Vector3.Zero();
  74188. this.L10 = BABYLON.Vector3.Zero();
  74189. this.L11 = BABYLON.Vector3.Zero();
  74190. this.L2_2 = BABYLON.Vector3.Zero();
  74191. this.L2_1 = BABYLON.Vector3.Zero();
  74192. this.L20 = BABYLON.Vector3.Zero();
  74193. this.L21 = BABYLON.Vector3.Zero();
  74194. this.L22 = BABYLON.Vector3.Zero();
  74195. }
  74196. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  74197. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74198. var c = colorVector.scale(deltaSolidAngle);
  74199. this.L00 = this.L00.add(c.scale(0.282095));
  74200. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  74201. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  74202. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  74203. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  74204. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  74205. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  74206. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  74207. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  74208. };
  74209. SphericalHarmonics.prototype.scale = function (scale) {
  74210. this.L00 = this.L00.scale(scale);
  74211. this.L1_1 = this.L1_1.scale(scale);
  74212. this.L10 = this.L10.scale(scale);
  74213. this.L11 = this.L11.scale(scale);
  74214. this.L2_2 = this.L2_2.scale(scale);
  74215. this.L2_1 = this.L2_1.scale(scale);
  74216. this.L20 = this.L20.scale(scale);
  74217. this.L21 = this.L21.scale(scale);
  74218. this.L22 = this.L22.scale(scale);
  74219. };
  74220. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  74221. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  74222. //
  74223. // E_lm = A_l * L_lm
  74224. //
  74225. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  74226. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  74227. // the scaling factors are given in equation 9.
  74228. // Constant (Band 0)
  74229. this.L00 = this.L00.scale(3.141593);
  74230. // Linear (Band 1)
  74231. this.L1_1 = this.L1_1.scale(2.094395);
  74232. this.L10 = this.L10.scale(2.094395);
  74233. this.L11 = this.L11.scale(2.094395);
  74234. // Quadratic (Band 2)
  74235. this.L2_2 = this.L2_2.scale(0.785398);
  74236. this.L2_1 = this.L2_1.scale(0.785398);
  74237. this.L20 = this.L20.scale(0.785398);
  74238. this.L21 = this.L21.scale(0.785398);
  74239. this.L22 = this.L22.scale(0.785398);
  74240. };
  74241. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  74242. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  74243. // L = (1/pi) * E * rho
  74244. //
  74245. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  74246. this.scale(1.0 / Math.PI);
  74247. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  74248. // (The pixel shader must apply albedo after texture fetches, etc).
  74249. };
  74250. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  74251. var result = new SphericalHarmonics();
  74252. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  74253. result.L1_1 = polynomial.y.scale(0.977204);
  74254. result.L10 = polynomial.z.scale(0.977204);
  74255. result.L11 = polynomial.x.scale(0.977204);
  74256. result.L2_2 = polynomial.xy.scale(1.16538);
  74257. result.L2_1 = polynomial.yz.scale(1.16538);
  74258. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  74259. result.L21 = polynomial.zx.scale(1.16538);
  74260. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  74261. result.scale(Math.PI);
  74262. return result;
  74263. };
  74264. return SphericalHarmonics;
  74265. }());
  74266. BABYLON.SphericalHarmonics = SphericalHarmonics;
  74267. })(BABYLON || (BABYLON = {}));
  74268. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  74269. "use strict";
  74270. var BABYLON;
  74271. (function (BABYLON) {
  74272. var FileFaceOrientation = /** @class */ (function () {
  74273. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  74274. this.name = name;
  74275. this.worldAxisForNormal = worldAxisForNormal;
  74276. this.worldAxisForFileX = worldAxisForFileX;
  74277. this.worldAxisForFileY = worldAxisForFileY;
  74278. }
  74279. return FileFaceOrientation;
  74280. }());
  74281. ;
  74282. /**
  74283. * Helper class dealing with the extraction of spherical polynomial dataArray
  74284. * from a cube map.
  74285. */
  74286. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  74287. function CubeMapToSphericalPolynomialTools() {
  74288. }
  74289. /**
  74290. * Converts a texture to the according Spherical Polynomial data.
  74291. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74292. *
  74293. * @param texture The texture to extract the information from.
  74294. * @return The Spherical Polynomial data.
  74295. */
  74296. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  74297. if (!texture.isCube) {
  74298. // Only supports cube Textures currently.
  74299. return null;
  74300. }
  74301. var size = texture.getSize().width;
  74302. var right = texture.readPixels(0);
  74303. var left = texture.readPixels(1);
  74304. var up;
  74305. var down;
  74306. if (texture.isRenderTarget) {
  74307. up = texture.readPixels(3);
  74308. down = texture.readPixels(2);
  74309. }
  74310. else {
  74311. up = texture.readPixels(2);
  74312. down = texture.readPixels(3);
  74313. }
  74314. var front = texture.readPixels(4);
  74315. var back = texture.readPixels(5);
  74316. var gammaSpace = texture.gammaSpace;
  74317. // Always read as RGBA.
  74318. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  74319. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74320. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74321. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74322. }
  74323. var cubeInfo = {
  74324. size: size,
  74325. right: right,
  74326. left: left,
  74327. up: up,
  74328. down: down,
  74329. front: front,
  74330. back: back,
  74331. format: format,
  74332. type: type,
  74333. gammaSpace: gammaSpace,
  74334. };
  74335. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  74336. };
  74337. /**
  74338. * Converts a cubemap to the according Spherical Polynomial data.
  74339. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74340. *
  74341. * @param cubeInfo The Cube map to extract the information from.
  74342. * @return The Spherical Polynomial data.
  74343. */
  74344. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  74345. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  74346. var totalSolidAngle = 0.0;
  74347. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  74348. var du = 2.0 / cubeInfo.size;
  74349. var dv = du;
  74350. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  74351. var minUV = du * 0.5 - 1.0;
  74352. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74353. var fileFace = this.FileFaces[faceIndex];
  74354. var dataArray = cubeInfo[fileFace.name];
  74355. var v = minUV;
  74356. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  74357. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  74358. // Because SP is still linear, so summation is fine in that basis.
  74359. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  74360. for (var y = 0; y < cubeInfo.size; y++) {
  74361. var u = minUV;
  74362. for (var x = 0; x < cubeInfo.size; x++) {
  74363. // World direction (not normalised)
  74364. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  74365. worldDirection.normalize();
  74366. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  74367. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  74368. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  74369. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  74370. // Handle Integer types.
  74371. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74372. r /= 255;
  74373. g /= 255;
  74374. b /= 255;
  74375. }
  74376. // Handle Gamma space textures.
  74377. if (cubeInfo.gammaSpace) {
  74378. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  74379. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  74380. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  74381. }
  74382. var color = new BABYLON.Color3(r, g, b);
  74383. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  74384. totalSolidAngle += deltaSolidAngle;
  74385. u += du;
  74386. }
  74387. v += dv;
  74388. }
  74389. }
  74390. // Solid angle for entire sphere is 4*pi
  74391. var sphereSolidAngle = 4.0 * Math.PI;
  74392. // Adjust the solid angle to allow for how many faces we processed.
  74393. var facesProcessed = 6.0;
  74394. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  74395. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  74396. // This is needed because the numerical integration over the cube uses a
  74397. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  74398. // and also to compensate for accumulative error due to float precision in the summation.
  74399. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  74400. sphericalHarmonics.scale(correctionFactor);
  74401. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  74402. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  74403. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  74404. };
  74405. CubeMapToSphericalPolynomialTools.FileFaces = [
  74406. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  74407. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  74408. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  74409. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  74410. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  74411. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  74412. ];
  74413. return CubeMapToSphericalPolynomialTools;
  74414. }());
  74415. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  74416. })(BABYLON || (BABYLON = {}));
  74417. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  74418. "use strict";
  74419. var BABYLON;
  74420. (function (BABYLON) {
  74421. /**
  74422. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  74423. */
  74424. var PanoramaToCubeMapTools = /** @class */ (function () {
  74425. function PanoramaToCubeMapTools() {
  74426. }
  74427. /**
  74428. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  74429. *
  74430. * @param float32Array The source data.
  74431. * @param inputWidth The width of the input panorama.
  74432. * @param inputhHeight The height of the input panorama.
  74433. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  74434. * @return The cubemap data
  74435. */
  74436. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  74437. if (!float32Array) {
  74438. throw "ConvertPanoramaToCubemap: input cannot be null";
  74439. }
  74440. if (float32Array.length != inputWidth * inputHeight * 3) {
  74441. throw "ConvertPanoramaToCubemap: input size is wrong";
  74442. }
  74443. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  74444. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  74445. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  74446. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  74447. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  74448. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  74449. return {
  74450. front: textureFront,
  74451. back: textureBack,
  74452. left: textureLeft,
  74453. right: textureRight,
  74454. up: textureUp,
  74455. down: textureDown,
  74456. size: size,
  74457. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  74458. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  74459. gammaSpace: false,
  74460. };
  74461. };
  74462. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  74463. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  74464. var textureArray = new Float32Array(buffer);
  74465. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  74466. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  74467. var dy = 1 / texSize;
  74468. var fy = 0;
  74469. for (var y = 0; y < texSize; y++) {
  74470. var xv1 = faceData[0];
  74471. var xv2 = faceData[2];
  74472. for (var x = 0; x < texSize; x++) {
  74473. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  74474. v.normalize();
  74475. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  74476. // 3 channels per pixels
  74477. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  74478. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  74479. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  74480. xv1 = xv1.add(rotDX1);
  74481. xv2 = xv2.add(rotDX2);
  74482. }
  74483. fy += dy;
  74484. }
  74485. return textureArray;
  74486. };
  74487. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  74488. var theta = Math.atan2(vDir.z, vDir.x);
  74489. var phi = Math.acos(vDir.y);
  74490. while (theta < -Math.PI)
  74491. theta += 2 * Math.PI;
  74492. while (theta > Math.PI)
  74493. theta -= 2 * Math.PI;
  74494. var dx = theta / Math.PI;
  74495. var dy = phi / Math.PI;
  74496. // recenter.
  74497. dx = dx * 0.5 + 0.5;
  74498. var px = Math.round(dx * inputWidth);
  74499. if (px < 0)
  74500. px = 0;
  74501. else if (px >= inputWidth)
  74502. px = inputWidth - 1;
  74503. var py = Math.round(dy * inputHeight);
  74504. if (py < 0)
  74505. py = 0;
  74506. else if (py >= inputHeight)
  74507. py = inputHeight - 1;
  74508. var inputY = (inputHeight - py - 1);
  74509. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  74510. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  74511. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  74512. return {
  74513. r: r,
  74514. g: g,
  74515. b: b
  74516. };
  74517. };
  74518. PanoramaToCubeMapTools.FACE_FRONT = [
  74519. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74520. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74521. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74522. new BABYLON.Vector3(1.0, 1.0, -1.0)
  74523. ];
  74524. PanoramaToCubeMapTools.FACE_BACK = [
  74525. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74526. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74527. new BABYLON.Vector3(1.0, 1.0, 1.0),
  74528. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  74529. ];
  74530. PanoramaToCubeMapTools.FACE_RIGHT = [
  74531. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74532. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74533. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74534. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74535. ];
  74536. PanoramaToCubeMapTools.FACE_LEFT = [
  74537. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74538. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74539. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74540. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  74541. ];
  74542. PanoramaToCubeMapTools.FACE_DOWN = [
  74543. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74544. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74545. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74546. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74547. ];
  74548. PanoramaToCubeMapTools.FACE_UP = [
  74549. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74550. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74551. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74552. new BABYLON.Vector3(1.0, -1.0, -1.0)
  74553. ];
  74554. return PanoramaToCubeMapTools;
  74555. }());
  74556. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  74557. })(BABYLON || (BABYLON = {}));
  74558. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  74559. "use strict";
  74560. var BABYLON;
  74561. (function (BABYLON) {
  74562. ;
  74563. /**
  74564. * This groups tools to convert HDR texture to native colors array.
  74565. */
  74566. var HDRTools = /** @class */ (function () {
  74567. function HDRTools() {
  74568. }
  74569. HDRTools.Ldexp = function (mantissa, exponent) {
  74570. if (exponent > 1023) {
  74571. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  74572. }
  74573. if (exponent < -1074) {
  74574. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  74575. }
  74576. return mantissa * Math.pow(2, exponent);
  74577. };
  74578. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  74579. if (exponent > 0) {
  74580. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  74581. float32array[index + 0] = red * exponent;
  74582. float32array[index + 1] = green * exponent;
  74583. float32array[index + 2] = blue * exponent;
  74584. }
  74585. else {
  74586. float32array[index + 0] = 0;
  74587. float32array[index + 1] = 0;
  74588. float32array[index + 2] = 0;
  74589. }
  74590. };
  74591. HDRTools.readStringLine = function (uint8array, startIndex) {
  74592. var line = "";
  74593. var character = "";
  74594. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  74595. character = String.fromCharCode(uint8array[i]);
  74596. if (character == "\n") {
  74597. break;
  74598. }
  74599. line += character;
  74600. }
  74601. return line;
  74602. };
  74603. /**
  74604. * Reads header information from an RGBE texture stored in a native array.
  74605. * More information on this format are available here:
  74606. * https://en.wikipedia.org/wiki/RGBE_image_format
  74607. *
  74608. * @param uint8array The binary file stored in native array.
  74609. * @return The header information.
  74610. */
  74611. HDRTools.RGBE_ReadHeader = function (uint8array) {
  74612. var height = 0;
  74613. var width = 0;
  74614. var line = this.readStringLine(uint8array, 0);
  74615. if (line[0] != '#' || line[1] != '?') {
  74616. throw "Bad HDR Format.";
  74617. }
  74618. var endOfHeader = false;
  74619. var findFormat = false;
  74620. var lineIndex = 0;
  74621. do {
  74622. lineIndex += (line.length + 1);
  74623. line = this.readStringLine(uint8array, lineIndex);
  74624. if (line == "FORMAT=32-bit_rle_rgbe") {
  74625. findFormat = true;
  74626. }
  74627. else if (line.length == 0) {
  74628. endOfHeader = true;
  74629. }
  74630. } while (!endOfHeader);
  74631. if (!findFormat) {
  74632. throw "HDR Bad header format, unsupported FORMAT";
  74633. }
  74634. lineIndex += (line.length + 1);
  74635. line = this.readStringLine(uint8array, lineIndex);
  74636. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  74637. var match = sizeRegexp.exec(line);
  74638. // TODO. Support +Y and -X if needed.
  74639. if (!match || match.length < 3) {
  74640. throw "HDR Bad header format, no size";
  74641. }
  74642. width = parseInt(match[2]);
  74643. height = parseInt(match[1]);
  74644. if (width < 8 || width > 0x7fff) {
  74645. throw "HDR Bad header format, unsupported size";
  74646. }
  74647. lineIndex += (line.length + 1);
  74648. return {
  74649. height: height,
  74650. width: width,
  74651. dataPosition: lineIndex
  74652. };
  74653. };
  74654. /**
  74655. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  74656. * This RGBE texture needs to store the information as a panorama.
  74657. *
  74658. * More information on this format are available here:
  74659. * https://en.wikipedia.org/wiki/RGBE_image_format
  74660. *
  74661. * @param buffer The binary file stored in an array buffer.
  74662. * @param size The expected size of the extracted cubemap.
  74663. * @return The Cube Map information.
  74664. */
  74665. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  74666. var uint8array = new Uint8Array(buffer);
  74667. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  74668. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  74669. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  74670. return cubeMapData;
  74671. };
  74672. /**
  74673. * Returns the pixels data extracted from an RGBE texture.
  74674. * This pixels will be stored left to right up to down in the R G B order in one array.
  74675. *
  74676. * More information on this format are available here:
  74677. * https://en.wikipedia.org/wiki/RGBE_image_format
  74678. *
  74679. * @param uint8array The binary file stored in an array buffer.
  74680. * @param hdrInfo The header information of the file.
  74681. * @return The pixels data in RGB right to left up to down order.
  74682. */
  74683. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  74684. // Keep for multi format supports.
  74685. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  74686. };
  74687. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  74688. var num_scanlines = hdrInfo.height;
  74689. var scanline_width = hdrInfo.width;
  74690. var a, b, c, d, count;
  74691. var dataIndex = hdrInfo.dataPosition;
  74692. var index = 0, endIndex = 0, i = 0;
  74693. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  74694. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  74695. // 3 channels of 4 bytes per pixel in float.
  74696. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  74697. var resultArray = new Float32Array(resultBuffer);
  74698. // read in each successive scanline
  74699. while (num_scanlines > 0) {
  74700. a = uint8array[dataIndex++];
  74701. b = uint8array[dataIndex++];
  74702. c = uint8array[dataIndex++];
  74703. d = uint8array[dataIndex++];
  74704. if (a != 2 || b != 2 || (c & 0x80)) {
  74705. // this file is not run length encoded
  74706. throw "HDR Bad header format, not RLE";
  74707. }
  74708. if (((c << 8) | d) != scanline_width) {
  74709. throw "HDR Bad header format, wrong scan line width";
  74710. }
  74711. index = 0;
  74712. // read each of the four channels for the scanline into the buffer
  74713. for (i = 0; i < 4; i++) {
  74714. endIndex = (i + 1) * scanline_width;
  74715. while (index < endIndex) {
  74716. a = uint8array[dataIndex++];
  74717. b = uint8array[dataIndex++];
  74718. if (a > 128) {
  74719. // a run of the same value
  74720. count = a - 128;
  74721. if ((count == 0) || (count > endIndex - index)) {
  74722. throw "HDR Bad Format, bad scanline data (run)";
  74723. }
  74724. while (count-- > 0) {
  74725. scanLineArray[index++] = b;
  74726. }
  74727. }
  74728. else {
  74729. // a non-run
  74730. count = a;
  74731. if ((count == 0) || (count > endIndex - index)) {
  74732. throw "HDR Bad Format, bad scanline data (non-run)";
  74733. }
  74734. scanLineArray[index++] = b;
  74735. if (--count > 0) {
  74736. for (var j = 0; j < count; j++) {
  74737. scanLineArray[index++] = uint8array[dataIndex++];
  74738. }
  74739. }
  74740. }
  74741. }
  74742. }
  74743. // now convert data from buffer into floats
  74744. for (i = 0; i < scanline_width; i++) {
  74745. a = scanLineArray[i];
  74746. b = scanLineArray[i + scanline_width];
  74747. c = scanLineArray[i + 2 * scanline_width];
  74748. d = scanLineArray[i + 3 * scanline_width];
  74749. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  74750. }
  74751. num_scanlines--;
  74752. }
  74753. return resultArray;
  74754. };
  74755. return HDRTools;
  74756. }());
  74757. BABYLON.HDRTools = HDRTools;
  74758. })(BABYLON || (BABYLON = {}));
  74759. //# sourceMappingURL=babylon.hdr.js.map
  74760. "use strict";
  74761. var BABYLON;
  74762. (function (BABYLON) {
  74763. /**
  74764. * This represents a texture coming from an HDR input.
  74765. *
  74766. * The only supported format is currently panorama picture stored in RGBE format.
  74767. * Example of such files can be found on HDRLib: http://hdrlib.com/
  74768. */
  74769. var HDRCubeTexture = /** @class */ (function (_super) {
  74770. __extends(HDRCubeTexture, _super);
  74771. /**
  74772. * Instantiates an HDRTexture from the following parameters.
  74773. *
  74774. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  74775. * @param scene The scene the texture will be used in
  74776. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  74777. * @param noMipmap Forces to not generate the mipmap if true
  74778. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  74779. * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  74780. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  74781. */
  74782. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  74783. if (noMipmap === void 0) { noMipmap = false; }
  74784. if (generateHarmonics === void 0) { generateHarmonics = true; }
  74785. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  74786. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  74787. if (onLoad === void 0) { onLoad = null; }
  74788. if (onError === void 0) { onError = null; }
  74789. var _this = _super.call(this, scene) || this;
  74790. _this._useInGammaSpace = false;
  74791. _this._generateHarmonics = true;
  74792. _this._isBABYLONPreprocessed = false;
  74793. _this._onLoad = null;
  74794. _this._onError = null;
  74795. /**
  74796. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  74797. */
  74798. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  74799. /**
  74800. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  74801. * This is usefull at run time to apply the good shader.
  74802. */
  74803. _this.isPMREM = false;
  74804. _this._isBlocking = true;
  74805. /**
  74806. * Gets or sets the center of the bounding box associated with the cube texture
  74807. * It must define where the camera used to render the texture was set
  74808. */
  74809. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  74810. if (!url) {
  74811. return _this;
  74812. }
  74813. _this.name = url;
  74814. _this.url = url;
  74815. _this.hasAlpha = false;
  74816. _this.isCube = true;
  74817. _this._textureMatrix = BABYLON.Matrix.Identity();
  74818. _this._onLoad = onLoad;
  74819. _this._onError = onError;
  74820. _this.gammaSpace = false;
  74821. var caps = scene.getEngine().getCaps();
  74822. if (size) {
  74823. _this._isBABYLONPreprocessed = false;
  74824. _this._noMipmap = noMipmap;
  74825. _this._size = size;
  74826. _this._useInGammaSpace = useInGammaSpace;
  74827. _this._usePMREMGenerator = usePMREMGenerator &&
  74828. caps.textureLOD &&
  74829. caps.textureFloat &&
  74830. !_this._useInGammaSpace;
  74831. }
  74832. else {
  74833. _this._isBABYLONPreprocessed = true;
  74834. _this._noMipmap = false;
  74835. _this._useInGammaSpace = false;
  74836. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  74837. !_this._useInGammaSpace;
  74838. }
  74839. _this.isPMREM = _this._usePMREMGenerator;
  74840. _this._texture = _this._getFromCache(url, _this._noMipmap);
  74841. if (!_this._texture) {
  74842. if (!scene.useDelayedTextureLoading) {
  74843. _this.loadTexture();
  74844. }
  74845. else {
  74846. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  74847. }
  74848. }
  74849. return _this;
  74850. }
  74851. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  74852. /**
  74853. * Gets wether or not the texture is blocking during loading.
  74854. */
  74855. get: function () {
  74856. return this._isBlocking;
  74857. },
  74858. /**
  74859. * Sets wether or not the texture is blocking during loading.
  74860. */
  74861. set: function (value) {
  74862. this._isBlocking = value;
  74863. },
  74864. enumerable: true,
  74865. configurable: true
  74866. });
  74867. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  74868. get: function () {
  74869. return this._boundingBoxSize;
  74870. },
  74871. /**
  74872. * Gets or sets the size of the bounding box associated with the cube texture
  74873. * When defined, the cubemap will switch to local mode
  74874. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  74875. * @example https://www.babylonjs-playground.com/#RNASML
  74876. */
  74877. set: function (value) {
  74878. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  74879. return;
  74880. }
  74881. this._boundingBoxSize = value;
  74882. var scene = this.getScene();
  74883. if (scene) {
  74884. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  74885. }
  74886. },
  74887. enumerable: true,
  74888. configurable: true
  74889. });
  74890. /**
  74891. * Occurs when the file is a preprocessed .babylon.hdr file.
  74892. */
  74893. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  74894. var _this = this;
  74895. var mipLevels = 0;
  74896. var floatArrayView = null;
  74897. var scene = this.getScene();
  74898. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  74899. var mips = new Array();
  74900. if (!floatArrayView) {
  74901. return mips;
  74902. }
  74903. var startIndex = 30;
  74904. for (var level = 0; level < mipLevels; level++) {
  74905. mips.push([]);
  74906. // Fill each pixel of the mip level.
  74907. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  74908. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74909. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  74910. mips[level].push(faceData);
  74911. startIndex += faceSize;
  74912. }
  74913. }
  74914. return mips;
  74915. } : null;
  74916. var callback = function (buffer) {
  74917. var scene = _this.getScene();
  74918. if (!scene) {
  74919. return null;
  74920. }
  74921. // Create Native Array Views
  74922. var intArrayView = new Int32Array(buffer);
  74923. floatArrayView = new Float32Array(buffer);
  74924. // Fill header.
  74925. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  74926. _this._size = intArrayView[1]; // CubeMap max mip face size.
  74927. // Update Texture Information.
  74928. if (!_this._texture) {
  74929. return null;
  74930. }
  74931. _this._texture.updateSize(_this._size, _this._size);
  74932. // Fill polynomial information.
  74933. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  74934. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  74935. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  74936. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  74937. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  74938. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  74939. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  74940. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  74941. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  74942. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  74943. _this.sphericalPolynomial = sphericalPolynomial;
  74944. // Fill pixel data.
  74945. mipLevels = intArrayView[29]; // Number of mip levels.
  74946. var startIndex = 30;
  74947. var data = [];
  74948. var faceSize = Math.pow(_this._size, 2) * 3;
  74949. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74950. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  74951. startIndex += faceSize;
  74952. }
  74953. var results = [];
  74954. var byteArray = null;
  74955. // Push each faces.
  74956. for (var k = 0; k < 6; k++) {
  74957. var dataFace = null;
  74958. // To be deprecated.
  74959. if (version === 1) {
  74960. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  74961. dataFace = data[j];
  74962. }
  74963. // If special cases.
  74964. if (!mipmapGenerator && dataFace) {
  74965. if (!scene.getEngine().getCaps().textureFloat) {
  74966. // 3 channels of 1 bytes per pixel in bytes.
  74967. var byteBuffer = new ArrayBuffer(faceSize);
  74968. byteArray = new Uint8Array(byteBuffer);
  74969. }
  74970. for (var i = 0; i < _this._size * _this._size; i++) {
  74971. // Put in gamma space if requested.
  74972. if (_this._useInGammaSpace) {
  74973. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  74974. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  74975. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  74976. }
  74977. // Convert to int texture for fallback.
  74978. if (byteArray) {
  74979. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  74980. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  74981. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  74982. // May use luminance instead if the result is not accurate.
  74983. var max = Math.max(Math.max(r, g), b);
  74984. if (max > 255) {
  74985. var scale = 255 / max;
  74986. r *= scale;
  74987. g *= scale;
  74988. b *= scale;
  74989. }
  74990. byteArray[(i * 3) + 0] = r;
  74991. byteArray[(i * 3) + 1] = g;
  74992. byteArray[(i * 3) + 2] = b;
  74993. }
  74994. }
  74995. }
  74996. // Fill the array accordingly.
  74997. if (byteArray) {
  74998. results.push(byteArray);
  74999. }
  75000. else {
  75001. results.push(dataFace);
  75002. }
  75003. }
  75004. return results;
  75005. };
  75006. if (scene) {
  75007. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  75008. }
  75009. };
  75010. /**
  75011. * Occurs when the file is raw .hdr file.
  75012. */
  75013. HDRCubeTexture.prototype.loadHDRTexture = function () {
  75014. var _this = this;
  75015. var callback = function (buffer) {
  75016. var scene = _this.getScene();
  75017. if (!scene) {
  75018. return null;
  75019. }
  75020. // Extract the raw linear data.
  75021. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  75022. // Generate harmonics if needed.
  75023. if (_this._generateHarmonics) {
  75024. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  75025. _this.sphericalPolynomial = sphericalPolynomial;
  75026. }
  75027. var results = [];
  75028. var byteArray = null;
  75029. // Push each faces.
  75030. for (var j = 0; j < 6; j++) {
  75031. // Create uintarray fallback.
  75032. if (!scene.getEngine().getCaps().textureFloat) {
  75033. // 3 channels of 1 bytes per pixel in bytes.
  75034. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  75035. byteArray = new Uint8Array(byteBuffer);
  75036. }
  75037. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  75038. // If special cases.
  75039. if (_this._useInGammaSpace || byteArray) {
  75040. for (var i = 0; i < _this._size * _this._size; i++) {
  75041. // Put in gamma space if requested.
  75042. if (_this._useInGammaSpace) {
  75043. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75044. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75045. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75046. }
  75047. // Convert to int texture for fallback.
  75048. if (byteArray) {
  75049. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75050. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75051. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75052. // May use luminance instead if the result is not accurate.
  75053. var max = Math.max(Math.max(r, g), b);
  75054. if (max > 255) {
  75055. var scale = 255 / max;
  75056. r *= scale;
  75057. g *= scale;
  75058. b *= scale;
  75059. }
  75060. byteArray[(i * 3) + 0] = r;
  75061. byteArray[(i * 3) + 1] = g;
  75062. byteArray[(i * 3) + 2] = b;
  75063. }
  75064. }
  75065. }
  75066. if (byteArray) {
  75067. results.push(byteArray);
  75068. }
  75069. else {
  75070. results.push(dataFace);
  75071. }
  75072. }
  75073. return results;
  75074. };
  75075. var mipmapGenerator = null;
  75076. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  75077. // if (!this._noMipmap &&
  75078. // this._usePMREMGenerator) {
  75079. // mipmapGenerator = (data: ArrayBufferView[]) => {
  75080. // // Custom setup of the generator matching with the PBR shader values.
  75081. // var generator = new BABYLON.PMREMGenerator(data,
  75082. // this._size,
  75083. // this._size,
  75084. // 0,
  75085. // 3,
  75086. // this.getScene().getEngine().getCaps().textureFloat,
  75087. // 2048,
  75088. // 0.25,
  75089. // false,
  75090. // true);
  75091. // return generator.filterCubeMap();
  75092. // };
  75093. // }
  75094. var scene = this.getScene();
  75095. if (scene) {
  75096. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  75097. }
  75098. };
  75099. /**
  75100. * Starts the loading process of the texture.
  75101. */
  75102. HDRCubeTexture.prototype.loadTexture = function () {
  75103. if (this._isBABYLONPreprocessed) {
  75104. this.loadBabylonTexture();
  75105. }
  75106. else {
  75107. this.loadHDRTexture();
  75108. }
  75109. };
  75110. HDRCubeTexture.prototype.clone = function () {
  75111. var scene = this.getScene();
  75112. if (!scene) {
  75113. return this;
  75114. }
  75115. var size = (this._isBABYLONPreprocessed ? null : this._size);
  75116. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  75117. // Base texture
  75118. newTexture.level = this.level;
  75119. newTexture.wrapU = this.wrapU;
  75120. newTexture.wrapV = this.wrapV;
  75121. newTexture.coordinatesIndex = this.coordinatesIndex;
  75122. newTexture.coordinatesMode = this.coordinatesMode;
  75123. return newTexture;
  75124. };
  75125. // Methods
  75126. HDRCubeTexture.prototype.delayLoad = function () {
  75127. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  75128. return;
  75129. }
  75130. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  75131. this._texture = this._getFromCache(this.url, this._noMipmap);
  75132. if (!this._texture) {
  75133. this.loadTexture();
  75134. }
  75135. };
  75136. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  75137. return this._textureMatrix;
  75138. };
  75139. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  75140. this._textureMatrix = value;
  75141. };
  75142. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  75143. var texture = null;
  75144. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  75145. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  75146. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  75147. texture.name = parsedTexture.name;
  75148. texture.hasAlpha = parsedTexture.hasAlpha;
  75149. texture.level = parsedTexture.level;
  75150. texture.coordinatesMode = parsedTexture.coordinatesMode;
  75151. texture.isBlocking = parsedTexture.isBlocking;
  75152. }
  75153. if (texture) {
  75154. if (parsedTexture.boundingBoxPosition) {
  75155. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  75156. }
  75157. if (parsedTexture.boundingBoxSize) {
  75158. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  75159. }
  75160. }
  75161. return texture;
  75162. };
  75163. HDRCubeTexture.prototype.serialize = function () {
  75164. if (!this.name) {
  75165. return null;
  75166. }
  75167. var serializationObject = {};
  75168. serializationObject.name = this.name;
  75169. serializationObject.hasAlpha = this.hasAlpha;
  75170. serializationObject.isCube = true;
  75171. serializationObject.level = this.level;
  75172. serializationObject.size = this._size;
  75173. serializationObject.coordinatesMode = this.coordinatesMode;
  75174. serializationObject.useInGammaSpace = this._useInGammaSpace;
  75175. serializationObject.generateHarmonics = this._generateHarmonics;
  75176. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  75177. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  75178. serializationObject.customType = "BABYLON.HDRCubeTexture";
  75179. serializationObject.noMipmap = this._noMipmap;
  75180. serializationObject.isBlocking = this._isBlocking;
  75181. return serializationObject;
  75182. };
  75183. /**
  75184. * Saves as a file the data contained in the texture in a binary format.
  75185. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75186. * as the spherical used in the lighting.
  75187. * @param url The HDR file url.
  75188. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75189. * @param onError Method called if any error happens during download.
  75190. * @return The packed binary data.
  75191. */
  75192. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  75193. if (onError === void 0) { onError = null; }
  75194. var callback = function (buffer) {
  75195. var data = new Blob([buffer], { type: 'application/octet-stream' });
  75196. // Returns a URL you can use as a href.
  75197. var objUrl = window.URL.createObjectURL(data);
  75198. // Simulates a link to it and click to dowload.
  75199. var a = document.createElement("a");
  75200. document.body.appendChild(a);
  75201. a.style.display = "none";
  75202. a.href = objUrl;
  75203. a.download = "envmap.babylon.hdr";
  75204. a.click();
  75205. };
  75206. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  75207. };
  75208. /**
  75209. * Serializes the data contained in the texture in a binary format.
  75210. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75211. * as the spherical used in the lighting.
  75212. * @param url The HDR file url.
  75213. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75214. * @param onError Method called if any error happens during download.
  75215. * @return The packed binary data.
  75216. */
  75217. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  75218. if (onError === void 0) { onError = null; }
  75219. // Needs the url tho create the texture.
  75220. if (!url) {
  75221. return;
  75222. }
  75223. // Check Power of two size.
  75224. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  75225. return;
  75226. }
  75227. // Coming Back in 3.x.
  75228. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  75229. };
  75230. HDRCubeTexture._facesMapping = [
  75231. "right",
  75232. "left",
  75233. "up",
  75234. "down",
  75235. "front",
  75236. "back"
  75237. ];
  75238. return HDRCubeTexture;
  75239. }(BABYLON.BaseTexture));
  75240. BABYLON.HDRCubeTexture = HDRCubeTexture;
  75241. })(BABYLON || (BABYLON = {}));
  75242. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  75243. "use strict";
  75244. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  75245. // Huge respect for a such great lib.
  75246. // Earcut license:
  75247. // Copyright (c) 2016, Mapbox
  75248. //
  75249. // Permission to use, copy, modify, and/or distribute this software for any purpose
  75250. // with or without fee is hereby granted, provided that the above copyright notice
  75251. // and this permission notice appear in all copies.
  75252. //
  75253. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  75254. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  75255. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  75256. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  75257. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  75258. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  75259. // THIS SOFTWARE.
  75260. var Earcut;
  75261. (function (Earcut) {
  75262. /**
  75263. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  75264. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  75265. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  75266. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  75267. */
  75268. function earcut(data, holeIndices, dim) {
  75269. dim = dim || 2;
  75270. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  75271. if (!outerNode)
  75272. return triangles;
  75273. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  75274. if (hasHoles)
  75275. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  75276. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  75277. if (data.length > 80 * dim) {
  75278. minX = maxX = data[0];
  75279. minY = maxY = data[1];
  75280. for (var i = dim; i < outerLen; i += dim) {
  75281. x = data[i];
  75282. y = data[i + 1];
  75283. if (x < minX)
  75284. minX = x;
  75285. if (y < minY)
  75286. minY = y;
  75287. if (x > maxX)
  75288. maxX = x;
  75289. if (y > maxY)
  75290. maxY = y;
  75291. }
  75292. // minX, minY and size are later used to transform coords into integers for z-order calculation
  75293. size = Math.max(maxX - minX, maxY - minY);
  75294. }
  75295. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  75296. return triangles;
  75297. }
  75298. Earcut.earcut = earcut;
  75299. var Node = /** @class */ (function () {
  75300. function Node(i, x, y) {
  75301. this.i = i;
  75302. this.x = x;
  75303. this.y = y;
  75304. this.prev = null;
  75305. this.next = null;
  75306. this.z = null;
  75307. this.prevZ = null;
  75308. this.nextZ = null;
  75309. this.steiner = false;
  75310. }
  75311. return Node;
  75312. }());
  75313. // create a circular doubly linked list from polygon points in the specified winding order
  75314. function linkedList(data, start, end, dim, clockwise) {
  75315. var i, last = null;
  75316. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  75317. for (i = start; i < end; i += dim)
  75318. last = insertNode(i, data[i], data[i + 1], last);
  75319. }
  75320. else {
  75321. for (i = end - dim; i >= start; i -= dim)
  75322. last = insertNode(i, data[i], data[i + 1], last);
  75323. }
  75324. if (last && equals(last, last.next)) {
  75325. removeNode(last);
  75326. last = last.next;
  75327. }
  75328. return last;
  75329. }
  75330. // eliminate colinear or duplicate points
  75331. function filterPoints(start, end) {
  75332. if (!start)
  75333. return start;
  75334. if (!end)
  75335. end = start;
  75336. var p = start, again;
  75337. do {
  75338. again = false;
  75339. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  75340. removeNode(p);
  75341. p = end = p.prev;
  75342. if (p === p.next)
  75343. return undefined;
  75344. again = true;
  75345. }
  75346. else {
  75347. p = p.next;
  75348. }
  75349. } while (again || p !== end);
  75350. return end;
  75351. }
  75352. // main ear slicing loop which triangulates a polygon (given as a linked list)
  75353. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  75354. if (!ear)
  75355. return;
  75356. // interlink polygon nodes in z-order
  75357. if (!pass && size)
  75358. indexCurve(ear, minX, minY, size);
  75359. var stop = ear, prev, next;
  75360. // iterate through ears, slicing them one by one
  75361. while (ear.prev !== ear.next) {
  75362. prev = ear.prev;
  75363. next = ear.next;
  75364. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  75365. // cut off the triangle
  75366. triangles.push(prev.i / dim);
  75367. triangles.push(ear.i / dim);
  75368. triangles.push(next.i / dim);
  75369. removeNode(ear);
  75370. // skipping the next vertice leads to less sliver triangles
  75371. ear = next.next;
  75372. stop = next.next;
  75373. continue;
  75374. }
  75375. ear = next;
  75376. // if we looped through the whole remaining polygon and can't find any more ears
  75377. if (ear === stop) {
  75378. // try filtering points and slicing again
  75379. if (!pass) {
  75380. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  75381. // if this didn't work, try curing all small self-intersections locally
  75382. }
  75383. else if (pass === 1) {
  75384. ear = cureLocalIntersections(ear, triangles, dim);
  75385. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  75386. // as a last resort, try splitting the remaining polygon into two
  75387. }
  75388. else if (pass === 2) {
  75389. splitEarcut(ear, triangles, dim, minX, minY, size);
  75390. }
  75391. break;
  75392. }
  75393. }
  75394. }
  75395. // check whether a polygon node forms a valid ear with adjacent nodes
  75396. function isEar(ear) {
  75397. var a = ear.prev, b = ear, c = ear.next;
  75398. if (area(a, b, c) >= 0)
  75399. return false; // reflex, can't be an ear
  75400. // now make sure we don't have other points inside the potential ear
  75401. var p = ear.next.next;
  75402. while (p !== ear.prev) {
  75403. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75404. area(p.prev, p, p.next) >= 0)
  75405. return false;
  75406. p = p.next;
  75407. }
  75408. return true;
  75409. }
  75410. function isEarHashed(ear, minX, minY, size) {
  75411. var a = ear.prev, b = ear, c = ear.next;
  75412. if (area(a, b, c) >= 0)
  75413. return false; // reflex, can't be an ear
  75414. // triangle bbox; min & max are calculated like this for speed
  75415. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  75416. // z-order range for the current triangle bbox;
  75417. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  75418. // first look for points inside the triangle in increasing z-order
  75419. var p = ear.nextZ;
  75420. while (p && p.z <= maxZ) {
  75421. if (p !== ear.prev &&
  75422. p !== ear.next &&
  75423. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75424. area(p.prev, p, p.next) >= 0)
  75425. return false;
  75426. p = p.nextZ;
  75427. }
  75428. // then look for points in decreasing z-order
  75429. p = ear.prevZ;
  75430. while (p && p.z >= minZ) {
  75431. if (p !== ear.prev &&
  75432. p !== ear.next &&
  75433. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75434. area(p.prev, p, p.next) >= 0)
  75435. return false;
  75436. p = p.prevZ;
  75437. }
  75438. return true;
  75439. }
  75440. // go through all polygon nodes and cure small local self-intersections
  75441. function cureLocalIntersections(start, triangles, dim) {
  75442. var p = start;
  75443. do {
  75444. var a = p.prev, b = p.next.next;
  75445. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  75446. triangles.push(a.i / dim);
  75447. triangles.push(p.i / dim);
  75448. triangles.push(b.i / dim);
  75449. // remove two nodes involved
  75450. removeNode(p);
  75451. removeNode(p.next);
  75452. p = start = b;
  75453. }
  75454. p = p.next;
  75455. } while (p !== start);
  75456. return p;
  75457. }
  75458. // try splitting polygon into two and triangulate them independently
  75459. function splitEarcut(start, triangles, dim, minX, minY, size) {
  75460. // look for a valid diagonal that divides the polygon into two
  75461. var a = start;
  75462. do {
  75463. var b = a.next.next;
  75464. while (b !== a.prev) {
  75465. if (a.i !== b.i && isValidDiagonal(a, b)) {
  75466. // split the polygon in two by the diagonal
  75467. var c = splitPolygon(a, b);
  75468. // filter colinear points around the cuts
  75469. a = filterPoints(a, a.next);
  75470. c = filterPoints(c, c.next);
  75471. // run earcut on each half
  75472. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  75473. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  75474. return;
  75475. }
  75476. b = b.next;
  75477. }
  75478. a = a.next;
  75479. } while (a !== start);
  75480. }
  75481. // link every hole into the outer loop, producing a single-ring polygon without holes
  75482. function eliminateHoles(data, holeIndices, outerNode, dim) {
  75483. var queue = [], i, len, start, end, list;
  75484. for (i = 0, len = holeIndices.length; i < len; i++) {
  75485. start = holeIndices[i] * dim;
  75486. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75487. list = linkedList(data, start, end, dim, false);
  75488. if (list === list.next)
  75489. list.steiner = true;
  75490. queue.push(getLeftmost(list));
  75491. }
  75492. queue.sort(compareX);
  75493. // process holes from left to right
  75494. for (i = 0; i < queue.length; i++) {
  75495. eliminateHole(queue[i], outerNode);
  75496. outerNode = filterPoints(outerNode, outerNode.next);
  75497. }
  75498. return outerNode;
  75499. }
  75500. function compareX(a, b) {
  75501. return a.x - b.x;
  75502. }
  75503. // find a bridge between vertices that connects hole with an outer ring and and link it
  75504. function eliminateHole(hole, outerNode) {
  75505. outerNode = findHoleBridge(hole, outerNode);
  75506. if (outerNode) {
  75507. var b = splitPolygon(outerNode, hole);
  75508. filterPoints(b, b.next);
  75509. }
  75510. }
  75511. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  75512. function findHoleBridge(hole, outerNode) {
  75513. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  75514. // find a segment intersected by a ray from the hole's leftmost point to the left;
  75515. // segment's endpoint with lesser x will be potential connection point
  75516. do {
  75517. if (hy <= p.y && hy >= p.next.y) {
  75518. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  75519. if (x <= hx && x > qx) {
  75520. qx = x;
  75521. if (x === hx) {
  75522. if (hy === p.y)
  75523. return p;
  75524. if (hy === p.next.y)
  75525. return p.next;
  75526. }
  75527. m = p.x < p.next.x ? p : p.next;
  75528. }
  75529. }
  75530. p = p.next;
  75531. } while (p !== outerNode);
  75532. if (!m)
  75533. return null;
  75534. if (hx === qx)
  75535. return m.prev; // hole touches outer segment; pick lower endpoint
  75536. // look for points inside the triangle of hole point, segment intersection and endpoint;
  75537. // if there are no points found, we have a valid connection;
  75538. // otherwise choose the point of the minimum angle with the ray as connection point
  75539. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  75540. p = m.next;
  75541. while (p !== stop) {
  75542. if (hx >= p.x &&
  75543. p.x >= mx &&
  75544. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  75545. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  75546. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  75547. m = p;
  75548. tanMin = tan;
  75549. }
  75550. }
  75551. p = p.next;
  75552. }
  75553. return m;
  75554. }
  75555. // interlink polygon nodes in z-order
  75556. function indexCurve(start, minX, minY, size) {
  75557. var p = start;
  75558. do {
  75559. if (p.z === null)
  75560. p.z = zOrder(p.x, p.y, minX, minY, size);
  75561. p.prevZ = p.prev;
  75562. p.nextZ = p.next;
  75563. p = p.next;
  75564. } while (p !== start);
  75565. p.prevZ.nextZ = null;
  75566. p.prevZ = null;
  75567. sortLinked(p);
  75568. }
  75569. // Simon Tatham's linked list merge sort algorithm
  75570. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  75571. function sortLinked(list) {
  75572. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  75573. do {
  75574. p = list;
  75575. list = null;
  75576. tail = null;
  75577. numMerges = 0;
  75578. while (p) {
  75579. numMerges++;
  75580. q = p;
  75581. pSize = 0;
  75582. for (i = 0; i < inSize; i++) {
  75583. pSize++;
  75584. q = q.nextZ;
  75585. if (!q)
  75586. break;
  75587. }
  75588. qSize = inSize;
  75589. while (pSize > 0 || (qSize > 0 && q)) {
  75590. if (pSize === 0) {
  75591. e = q;
  75592. q = q.nextZ;
  75593. qSize--;
  75594. }
  75595. else if (qSize === 0 || !q) {
  75596. e = p;
  75597. p = p.nextZ;
  75598. pSize--;
  75599. }
  75600. else if (p.z <= q.z) {
  75601. e = p;
  75602. p = p.nextZ;
  75603. pSize--;
  75604. }
  75605. else {
  75606. e = q;
  75607. q = q.nextZ;
  75608. qSize--;
  75609. }
  75610. if (tail)
  75611. tail.nextZ = e;
  75612. else
  75613. list = e;
  75614. e.prevZ = tail;
  75615. tail = e;
  75616. }
  75617. p = q;
  75618. }
  75619. tail.nextZ = null;
  75620. inSize *= 2;
  75621. } while (numMerges > 1);
  75622. return list;
  75623. }
  75624. // z-order of a point given coords and size of the data bounding box
  75625. function zOrder(x, y, minX, minY, size) {
  75626. // coords are transformed into non-negative 15-bit integer range
  75627. x = 32767 * (x - minX) / size;
  75628. y = 32767 * (y - minY) / size;
  75629. x = (x | (x << 8)) & 0x00FF00FF;
  75630. x = (x | (x << 4)) & 0x0F0F0F0F;
  75631. x = (x | (x << 2)) & 0x33333333;
  75632. x = (x | (x << 1)) & 0x55555555;
  75633. y = (y | (y << 8)) & 0x00FF00FF;
  75634. y = (y | (y << 4)) & 0x0F0F0F0F;
  75635. y = (y | (y << 2)) & 0x33333333;
  75636. y = (y | (y << 1)) & 0x55555555;
  75637. return x | (y << 1);
  75638. }
  75639. // find the leftmost node of a polygon ring
  75640. function getLeftmost(start) {
  75641. var p = start, leftmost = start;
  75642. do {
  75643. if (p.x < leftmost.x)
  75644. leftmost = p;
  75645. p = p.next;
  75646. } while (p !== start);
  75647. return leftmost;
  75648. }
  75649. // check if a point lies within a convex triangle
  75650. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  75651. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  75652. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  75653. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  75654. }
  75655. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  75656. function isValidDiagonal(a, b) {
  75657. return a.next.i !== b.i &&
  75658. a.prev.i !== b.i &&
  75659. !intersectsPolygon(a, b) &&
  75660. locallyInside(a, b) &&
  75661. locallyInside(b, a) &&
  75662. middleInside(a, b);
  75663. }
  75664. // signed area of a triangle
  75665. function area(p, q, r) {
  75666. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  75667. }
  75668. // check if two points are equal
  75669. function equals(p1, p2) {
  75670. return p1.x === p2.x && p1.y === p2.y;
  75671. }
  75672. // check if two segments intersect
  75673. function intersects(p1, q1, p2, q2) {
  75674. if ((equals(p1, q1) && equals(p2, q2)) ||
  75675. (equals(p1, q2) && equals(p2, q1)))
  75676. return true;
  75677. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  75678. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  75679. }
  75680. // check if a polygon diagonal intersects any polygon segments
  75681. function intersectsPolygon(a, b) {
  75682. var p = a;
  75683. do {
  75684. if (p.i !== a.i &&
  75685. p.next.i !== a.i &&
  75686. p.i !== b.i &&
  75687. p.next.i !== b.i &&
  75688. intersects(p, p.next, a, b))
  75689. return true;
  75690. p = p.next;
  75691. } while (p !== a);
  75692. return false;
  75693. }
  75694. // check if a polygon diagonal is locally inside the polygon
  75695. function locallyInside(a, b) {
  75696. return area(a.prev, a, a.next) < 0
  75697. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  75698. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  75699. }
  75700. // check if the middle point of a polygon diagonal is inside the polygon
  75701. function middleInside(a, b) {
  75702. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  75703. do {
  75704. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  75705. inside = !inside;
  75706. p = p.next;
  75707. } while (p !== a);
  75708. return inside;
  75709. }
  75710. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  75711. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  75712. function splitPolygon(a, b) {
  75713. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  75714. a.next = b;
  75715. b.prev = a;
  75716. a2.next = an;
  75717. an.prev = a2;
  75718. b2.next = a2;
  75719. a2.prev = b2;
  75720. bp.next = b2;
  75721. b2.prev = bp;
  75722. return b2;
  75723. }
  75724. // create a node and optionally link it with previous one (in a circular doubly linked list)
  75725. function insertNode(i, x, y, last) {
  75726. var p = new Node(i, x, y);
  75727. if (!last) {
  75728. p.prev = p;
  75729. p.next = p;
  75730. }
  75731. else {
  75732. p.next = last.next;
  75733. p.prev = last;
  75734. last.next.prev = p;
  75735. last.next = p;
  75736. }
  75737. return p;
  75738. }
  75739. function removeNode(p) {
  75740. p.next.prev = p.prev;
  75741. p.prev.next = p.next;
  75742. if (p.prevZ)
  75743. p.prevZ.nextZ = p.nextZ;
  75744. if (p.nextZ)
  75745. p.nextZ.prevZ = p.prevZ;
  75746. }
  75747. /**
  75748. * return a percentage difference between the polygon area and its triangulation area;
  75749. * used to verify correctness of triangulation
  75750. */
  75751. function deviation(data, holeIndices, dim, triangles) {
  75752. var hasHoles = holeIndices && holeIndices.length;
  75753. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  75754. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  75755. if (hasHoles) {
  75756. for (var i = 0, len = holeIndices.length; i < len; i++) {
  75757. var start = holeIndices[i] * dim;
  75758. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75759. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  75760. }
  75761. }
  75762. var trianglesArea = 0;
  75763. for (i = 0; i < triangles.length; i += 3) {
  75764. var a = triangles[i] * dim;
  75765. var b = triangles[i + 1] * dim;
  75766. var c = triangles[i + 2] * dim;
  75767. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  75768. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  75769. }
  75770. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  75771. }
  75772. Earcut.deviation = deviation;
  75773. ;
  75774. function signedArea(data, start, end, dim) {
  75775. var sum = 0;
  75776. for (var i = start, j = end - dim; i < end; i += dim) {
  75777. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  75778. j = i;
  75779. }
  75780. return sum;
  75781. }
  75782. /**
  75783. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  75784. */
  75785. function flatten(data) {
  75786. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  75787. for (var i = 0; i < data.length; i++) {
  75788. for (var j = 0; j < data[i].length; j++) {
  75789. for (var d = 0; d < dim; d++)
  75790. result.vertices.push(data[i][j][d]);
  75791. }
  75792. if (i > 0) {
  75793. holeIndex += data[i - 1].length;
  75794. result.holes.push(holeIndex);
  75795. }
  75796. }
  75797. return result;
  75798. }
  75799. Earcut.flatten = flatten;
  75800. ;
  75801. })(Earcut || (Earcut = {}));
  75802. //# sourceMappingURL=babylon.earcut.js.map
  75803. "use strict";
  75804. var BABYLON;
  75805. (function (BABYLON) {
  75806. var IndexedVector2 = /** @class */ (function (_super) {
  75807. __extends(IndexedVector2, _super);
  75808. function IndexedVector2(original, index) {
  75809. var _this = _super.call(this, original.x, original.y) || this;
  75810. _this.index = index;
  75811. return _this;
  75812. }
  75813. return IndexedVector2;
  75814. }(BABYLON.Vector2));
  75815. var PolygonPoints = /** @class */ (function () {
  75816. function PolygonPoints() {
  75817. this.elements = new Array();
  75818. }
  75819. PolygonPoints.prototype.add = function (originalPoints) {
  75820. var _this = this;
  75821. var result = new Array();
  75822. originalPoints.forEach(function (point) {
  75823. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  75824. var newPoint = new IndexedVector2(point, _this.elements.length);
  75825. result.push(newPoint);
  75826. _this.elements.push(newPoint);
  75827. }
  75828. });
  75829. return result;
  75830. };
  75831. PolygonPoints.prototype.computeBounds = function () {
  75832. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75833. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75834. this.elements.forEach(function (point) {
  75835. // x
  75836. if (point.x < lmin.x) {
  75837. lmin.x = point.x;
  75838. }
  75839. else if (point.x > lmax.x) {
  75840. lmax.x = point.x;
  75841. }
  75842. // y
  75843. if (point.y < lmin.y) {
  75844. lmin.y = point.y;
  75845. }
  75846. else if (point.y > lmax.y) {
  75847. lmax.y = point.y;
  75848. }
  75849. });
  75850. return {
  75851. min: lmin,
  75852. max: lmax,
  75853. width: lmax.x - lmin.x,
  75854. height: lmax.y - lmin.y
  75855. };
  75856. };
  75857. return PolygonPoints;
  75858. }());
  75859. var Polygon = /** @class */ (function () {
  75860. function Polygon() {
  75861. }
  75862. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  75863. return [
  75864. new BABYLON.Vector2(xmin, ymin),
  75865. new BABYLON.Vector2(xmax, ymin),
  75866. new BABYLON.Vector2(xmax, ymax),
  75867. new BABYLON.Vector2(xmin, ymax)
  75868. ];
  75869. };
  75870. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  75871. if (cx === void 0) { cx = 0; }
  75872. if (cy === void 0) { cy = 0; }
  75873. if (numberOfSides === void 0) { numberOfSides = 32; }
  75874. var result = new Array();
  75875. var angle = 0;
  75876. var increment = (Math.PI * 2) / numberOfSides;
  75877. for (var i = 0; i < numberOfSides; i++) {
  75878. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  75879. angle -= increment;
  75880. }
  75881. return result;
  75882. };
  75883. Polygon.Parse = function (input) {
  75884. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  75885. var i, result = [];
  75886. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  75887. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  75888. }
  75889. return result;
  75890. };
  75891. Polygon.StartingAt = function (x, y) {
  75892. return BABYLON.Path2.StartingAt(x, y);
  75893. };
  75894. return Polygon;
  75895. }());
  75896. BABYLON.Polygon = Polygon;
  75897. var PolygonMeshBuilder = /** @class */ (function () {
  75898. function PolygonMeshBuilder(name, contours, scene) {
  75899. this._points = new PolygonPoints();
  75900. this._outlinepoints = new PolygonPoints();
  75901. this._holes = new Array();
  75902. this._epoints = new Array();
  75903. this._eholes = new Array();
  75904. this._name = name;
  75905. this._scene = scene;
  75906. var points;
  75907. if (contours instanceof BABYLON.Path2) {
  75908. points = contours.getPoints();
  75909. }
  75910. else {
  75911. points = contours;
  75912. }
  75913. this._addToepoint(points);
  75914. this._points.add(points);
  75915. this._outlinepoints.add(points);
  75916. }
  75917. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  75918. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  75919. var p = points_1[_i];
  75920. this._epoints.push(p.x, p.y);
  75921. }
  75922. };
  75923. PolygonMeshBuilder.prototype.addHole = function (hole) {
  75924. this._points.add(hole);
  75925. var holepoints = new PolygonPoints();
  75926. holepoints.add(hole);
  75927. this._holes.push(holepoints);
  75928. this._eholes.push(this._epoints.length / 2);
  75929. this._addToepoint(hole);
  75930. return this;
  75931. };
  75932. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  75933. var _this = this;
  75934. if (updatable === void 0) { updatable = false; }
  75935. if (depth === void 0) { depth = 0; }
  75936. var result = new BABYLON.Mesh(this._name, this._scene);
  75937. var normals = new Array();
  75938. var positions = new Array();
  75939. var uvs = new Array();
  75940. var bounds = this._points.computeBounds();
  75941. this._points.elements.forEach(function (p) {
  75942. normals.push(0, 1.0, 0);
  75943. positions.push(p.x, 0, p.y);
  75944. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  75945. });
  75946. var indices = new Array();
  75947. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  75948. for (var i = 0; i < res.length; i++) {
  75949. indices.push(res[i]);
  75950. }
  75951. if (depth > 0) {
  75952. var positionscount = (positions.length / 3); //get the current pointcount
  75953. this._points.elements.forEach(function (p) {
  75954. normals.push(0, -1.0, 0);
  75955. positions.push(p.x, -depth, p.y);
  75956. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  75957. });
  75958. var totalCount = indices.length;
  75959. for (var i = 0; i < totalCount; i += 3) {
  75960. var i0 = indices[i + 0];
  75961. var i1 = indices[i + 1];
  75962. var i2 = indices[i + 2];
  75963. indices.push(i2 + positionscount);
  75964. indices.push(i1 + positionscount);
  75965. indices.push(i0 + positionscount);
  75966. }
  75967. //Add the sides
  75968. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  75969. this._holes.forEach(function (hole) {
  75970. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  75971. });
  75972. }
  75973. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  75974. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  75975. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  75976. result.setIndices(indices);
  75977. return result;
  75978. };
  75979. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  75980. var StartIndex = positions.length / 3;
  75981. var ulength = 0;
  75982. for (var i = 0; i < points.elements.length; i++) {
  75983. var p = points.elements[i];
  75984. var p1;
  75985. if ((i + 1) > points.elements.length - 1) {
  75986. p1 = points.elements[0];
  75987. }
  75988. else {
  75989. p1 = points.elements[i + 1];
  75990. }
  75991. positions.push(p.x, 0, p.y);
  75992. positions.push(p.x, -depth, p.y);
  75993. positions.push(p1.x, 0, p1.y);
  75994. positions.push(p1.x, -depth, p1.y);
  75995. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  75996. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  75997. var v3 = v2.subtract(v1);
  75998. var v4 = new BABYLON.Vector3(0, 1, 0);
  75999. var vn = BABYLON.Vector3.Cross(v3, v4);
  76000. vn = vn.normalize();
  76001. uvs.push(ulength / bounds.width, 0);
  76002. uvs.push(ulength / bounds.width, 1);
  76003. ulength += v3.length();
  76004. uvs.push((ulength / bounds.width), 0);
  76005. uvs.push((ulength / bounds.width), 1);
  76006. if (!flip) {
  76007. normals.push(-vn.x, -vn.y, -vn.z);
  76008. normals.push(-vn.x, -vn.y, -vn.z);
  76009. normals.push(-vn.x, -vn.y, -vn.z);
  76010. normals.push(-vn.x, -vn.y, -vn.z);
  76011. indices.push(StartIndex);
  76012. indices.push(StartIndex + 1);
  76013. indices.push(StartIndex + 2);
  76014. indices.push(StartIndex + 1);
  76015. indices.push(StartIndex + 3);
  76016. indices.push(StartIndex + 2);
  76017. }
  76018. else {
  76019. normals.push(vn.x, vn.y, vn.z);
  76020. normals.push(vn.x, vn.y, vn.z);
  76021. normals.push(vn.x, vn.y, vn.z);
  76022. normals.push(vn.x, vn.y, vn.z);
  76023. indices.push(StartIndex);
  76024. indices.push(StartIndex + 2);
  76025. indices.push(StartIndex + 1);
  76026. indices.push(StartIndex + 1);
  76027. indices.push(StartIndex + 2);
  76028. indices.push(StartIndex + 3);
  76029. }
  76030. StartIndex += 4;
  76031. }
  76032. ;
  76033. };
  76034. return PolygonMeshBuilder;
  76035. }());
  76036. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  76037. })(BABYLON || (BABYLON = {}));
  76038. //# sourceMappingURL=babylon.polygonMesh.js.map
  76039. "use strict";
  76040. var BABYLON;
  76041. (function (BABYLON) {
  76042. // Unique ID when we import meshes from Babylon to CSG
  76043. var currentCSGMeshId = 0;
  76044. // # class Vertex
  76045. // Represents a vertex of a polygon. Use your own vertex class instead of this
  76046. // one to provide additional features like texture coordinates and vertex
  76047. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  76048. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  76049. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  76050. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  76051. // is not used anywhere else.
  76052. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  76053. var Vertex = /** @class */ (function () {
  76054. function Vertex(pos, normal, uv) {
  76055. this.pos = pos;
  76056. this.normal = normal;
  76057. this.uv = uv;
  76058. }
  76059. Vertex.prototype.clone = function () {
  76060. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  76061. };
  76062. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  76063. // orientation of a polygon is flipped.
  76064. Vertex.prototype.flip = function () {
  76065. this.normal = this.normal.scale(-1);
  76066. };
  76067. // Create a new vertex between this vertex and `other` by linearly
  76068. // interpolating all properties using a parameter of `t`. Subclasses should
  76069. // override this to interpolate additional properties.
  76070. Vertex.prototype.interpolate = function (other, t) {
  76071. 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));
  76072. };
  76073. return Vertex;
  76074. }());
  76075. // # class Plane
  76076. // Represents a plane in 3D space.
  76077. var Plane = /** @class */ (function () {
  76078. function Plane(normal, w) {
  76079. this.normal = normal;
  76080. this.w = w;
  76081. }
  76082. Plane.FromPoints = function (a, b, c) {
  76083. var v0 = c.subtract(a);
  76084. var v1 = b.subtract(a);
  76085. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  76086. return null;
  76087. }
  76088. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  76089. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  76090. };
  76091. Plane.prototype.clone = function () {
  76092. return new Plane(this.normal.clone(), this.w);
  76093. };
  76094. Plane.prototype.flip = function () {
  76095. this.normal.scaleInPlace(-1);
  76096. this.w = -this.w;
  76097. };
  76098. // Split `polygon` by this plane if needed, then put the polygon or polygon
  76099. // fragments in the appropriate lists. Coplanar polygons go into either
  76100. // `coplanarFront` or `coplanarBack` depending on their orientation with
  76101. // respect to this plane. Polygons in front or in back of this plane go into
  76102. // either `front` or `back`.
  76103. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  76104. var COPLANAR = 0;
  76105. var FRONT = 1;
  76106. var BACK = 2;
  76107. var SPANNING = 3;
  76108. // Classify each point as well as the entire polygon into one of the above
  76109. // four classes.
  76110. var polygonType = 0;
  76111. var types = [];
  76112. var i;
  76113. var t;
  76114. for (i = 0; i < polygon.vertices.length; i++) {
  76115. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  76116. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  76117. polygonType |= type;
  76118. types.push(type);
  76119. }
  76120. // Put the polygon in the correct list, splitting it when necessary.
  76121. switch (polygonType) {
  76122. case COPLANAR:
  76123. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  76124. break;
  76125. case FRONT:
  76126. front.push(polygon);
  76127. break;
  76128. case BACK:
  76129. back.push(polygon);
  76130. break;
  76131. case SPANNING:
  76132. var f = [], b = [];
  76133. for (i = 0; i < polygon.vertices.length; i++) {
  76134. var j = (i + 1) % polygon.vertices.length;
  76135. var ti = types[i], tj = types[j];
  76136. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  76137. if (ti !== BACK)
  76138. f.push(vi);
  76139. if (ti !== FRONT)
  76140. b.push(ti !== BACK ? vi.clone() : vi);
  76141. if ((ti | tj) === SPANNING) {
  76142. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  76143. var v = vi.interpolate(vj, t);
  76144. f.push(v);
  76145. b.push(v.clone());
  76146. }
  76147. }
  76148. var poly;
  76149. if (f.length >= 3) {
  76150. poly = new Polygon(f, polygon.shared);
  76151. if (poly.plane)
  76152. front.push(poly);
  76153. }
  76154. if (b.length >= 3) {
  76155. poly = new Polygon(b, polygon.shared);
  76156. if (poly.plane)
  76157. back.push(poly);
  76158. }
  76159. break;
  76160. }
  76161. };
  76162. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  76163. // point is on the plane.
  76164. Plane.EPSILON = 1e-5;
  76165. return Plane;
  76166. }());
  76167. // # class Polygon
  76168. // Represents a convex polygon. The vertices used to initialize a polygon must
  76169. // be coplanar and form a convex loop.
  76170. //
  76171. // Each convex polygon has a `shared` property, which is shared between all
  76172. // polygons that are clones of each other or were split from the same polygon.
  76173. // This can be used to define per-polygon properties (such as surface color).
  76174. var Polygon = /** @class */ (function () {
  76175. function Polygon(vertices, shared) {
  76176. this.vertices = vertices;
  76177. this.shared = shared;
  76178. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  76179. }
  76180. Polygon.prototype.clone = function () {
  76181. var vertices = this.vertices.map(function (v) { return v.clone(); });
  76182. return new Polygon(vertices, this.shared);
  76183. };
  76184. Polygon.prototype.flip = function () {
  76185. this.vertices.reverse().map(function (v) { v.flip(); });
  76186. this.plane.flip();
  76187. };
  76188. return Polygon;
  76189. }());
  76190. // # class Node
  76191. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  76192. // by picking a polygon to split along. That polygon (and all other coplanar
  76193. // polygons) are added directly to that node and the other polygons are added to
  76194. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  76195. // no distinction between internal and leaf nodes.
  76196. var Node = /** @class */ (function () {
  76197. function Node(polygons) {
  76198. this.plane = null;
  76199. this.front = null;
  76200. this.back = null;
  76201. this.polygons = new Array();
  76202. if (polygons) {
  76203. this.build(polygons);
  76204. }
  76205. }
  76206. Node.prototype.clone = function () {
  76207. var node = new Node();
  76208. node.plane = this.plane && this.plane.clone();
  76209. node.front = this.front && this.front.clone();
  76210. node.back = this.back && this.back.clone();
  76211. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  76212. return node;
  76213. };
  76214. // Convert solid space to empty space and empty space to solid space.
  76215. Node.prototype.invert = function () {
  76216. for (var i = 0; i < this.polygons.length; i++) {
  76217. this.polygons[i].flip();
  76218. }
  76219. if (this.plane) {
  76220. this.plane.flip();
  76221. }
  76222. if (this.front) {
  76223. this.front.invert();
  76224. }
  76225. if (this.back) {
  76226. this.back.invert();
  76227. }
  76228. var temp = this.front;
  76229. this.front = this.back;
  76230. this.back = temp;
  76231. };
  76232. // Recursively remove all polygons in `polygons` that are inside this BSP
  76233. // tree.
  76234. Node.prototype.clipPolygons = function (polygons) {
  76235. if (!this.plane)
  76236. return polygons.slice();
  76237. var front = new Array(), back = new Array();
  76238. for (var i = 0; i < polygons.length; i++) {
  76239. this.plane.splitPolygon(polygons[i], front, back, front, back);
  76240. }
  76241. if (this.front) {
  76242. front = this.front.clipPolygons(front);
  76243. }
  76244. if (this.back) {
  76245. back = this.back.clipPolygons(back);
  76246. }
  76247. else {
  76248. back = [];
  76249. }
  76250. return front.concat(back);
  76251. };
  76252. // Remove all polygons in this BSP tree that are inside the other BSP tree
  76253. // `bsp`.
  76254. Node.prototype.clipTo = function (bsp) {
  76255. this.polygons = bsp.clipPolygons(this.polygons);
  76256. if (this.front)
  76257. this.front.clipTo(bsp);
  76258. if (this.back)
  76259. this.back.clipTo(bsp);
  76260. };
  76261. // Return a list of all polygons in this BSP tree.
  76262. Node.prototype.allPolygons = function () {
  76263. var polygons = this.polygons.slice();
  76264. if (this.front)
  76265. polygons = polygons.concat(this.front.allPolygons());
  76266. if (this.back)
  76267. polygons = polygons.concat(this.back.allPolygons());
  76268. return polygons;
  76269. };
  76270. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  76271. // new polygons are filtered down to the bottom of the tree and become new
  76272. // nodes there. Each set of polygons is partitioned using the first polygon
  76273. // (no heuristic is used to pick a good split).
  76274. Node.prototype.build = function (polygons) {
  76275. if (!polygons.length)
  76276. return;
  76277. if (!this.plane)
  76278. this.plane = polygons[0].plane.clone();
  76279. var front = new Array(), back = new Array();
  76280. for (var i = 0; i < polygons.length; i++) {
  76281. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  76282. }
  76283. if (front.length) {
  76284. if (!this.front)
  76285. this.front = new Node();
  76286. this.front.build(front);
  76287. }
  76288. if (back.length) {
  76289. if (!this.back)
  76290. this.back = new Node();
  76291. this.back.build(back);
  76292. }
  76293. };
  76294. return Node;
  76295. }());
  76296. var CSG = /** @class */ (function () {
  76297. function CSG() {
  76298. this.polygons = new Array();
  76299. }
  76300. // Convert BABYLON.Mesh to BABYLON.CSG
  76301. CSG.FromMesh = function (mesh) {
  76302. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  76303. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  76304. if (mesh instanceof BABYLON.Mesh) {
  76305. mesh.computeWorldMatrix(true);
  76306. matrix = mesh.getWorldMatrix();
  76307. meshPosition = mesh.position.clone();
  76308. meshRotation = mesh.rotation.clone();
  76309. if (mesh.rotationQuaternion) {
  76310. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  76311. }
  76312. meshScaling = mesh.scaling.clone();
  76313. }
  76314. else {
  76315. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  76316. }
  76317. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  76318. var subMeshes = mesh.subMeshes;
  76319. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  76320. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  76321. vertices = [];
  76322. for (var j = 0; j < 3; j++) {
  76323. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  76324. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  76325. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  76326. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  76327. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  76328. vertex = new Vertex(position, normal, uv);
  76329. vertices.push(vertex);
  76330. }
  76331. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  76332. // To handle the case of degenerated triangle
  76333. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  76334. if (polygon.plane)
  76335. polygons.push(polygon);
  76336. }
  76337. }
  76338. var csg = CSG.FromPolygons(polygons);
  76339. csg.matrix = matrix;
  76340. csg.position = meshPosition;
  76341. csg.rotation = meshRotation;
  76342. csg.scaling = meshScaling;
  76343. csg.rotationQuaternion = meshRotationQuaternion;
  76344. currentCSGMeshId++;
  76345. return csg;
  76346. };
  76347. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  76348. CSG.FromPolygons = function (polygons) {
  76349. var csg = new CSG();
  76350. csg.polygons = polygons;
  76351. return csg;
  76352. };
  76353. CSG.prototype.clone = function () {
  76354. var csg = new CSG();
  76355. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  76356. csg.copyTransformAttributes(this);
  76357. return csg;
  76358. };
  76359. CSG.prototype.union = function (csg) {
  76360. var a = new Node(this.clone().polygons);
  76361. var b = new Node(csg.clone().polygons);
  76362. a.clipTo(b);
  76363. b.clipTo(a);
  76364. b.invert();
  76365. b.clipTo(a);
  76366. b.invert();
  76367. a.build(b.allPolygons());
  76368. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76369. };
  76370. CSG.prototype.unionInPlace = function (csg) {
  76371. var a = new Node(this.polygons);
  76372. var b = new Node(csg.polygons);
  76373. a.clipTo(b);
  76374. b.clipTo(a);
  76375. b.invert();
  76376. b.clipTo(a);
  76377. b.invert();
  76378. a.build(b.allPolygons());
  76379. this.polygons = a.allPolygons();
  76380. };
  76381. CSG.prototype.subtract = function (csg) {
  76382. var a = new Node(this.clone().polygons);
  76383. var b = new Node(csg.clone().polygons);
  76384. a.invert();
  76385. a.clipTo(b);
  76386. b.clipTo(a);
  76387. b.invert();
  76388. b.clipTo(a);
  76389. b.invert();
  76390. a.build(b.allPolygons());
  76391. a.invert();
  76392. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76393. };
  76394. CSG.prototype.subtractInPlace = function (csg) {
  76395. var a = new Node(this.polygons);
  76396. var b = new Node(csg.polygons);
  76397. a.invert();
  76398. a.clipTo(b);
  76399. b.clipTo(a);
  76400. b.invert();
  76401. b.clipTo(a);
  76402. b.invert();
  76403. a.build(b.allPolygons());
  76404. a.invert();
  76405. this.polygons = a.allPolygons();
  76406. };
  76407. CSG.prototype.intersect = function (csg) {
  76408. var a = new Node(this.clone().polygons);
  76409. var b = new Node(csg.clone().polygons);
  76410. a.invert();
  76411. b.clipTo(a);
  76412. b.invert();
  76413. a.clipTo(b);
  76414. b.clipTo(a);
  76415. a.build(b.allPolygons());
  76416. a.invert();
  76417. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76418. };
  76419. CSG.prototype.intersectInPlace = function (csg) {
  76420. var a = new Node(this.polygons);
  76421. var b = new Node(csg.polygons);
  76422. a.invert();
  76423. b.clipTo(a);
  76424. b.invert();
  76425. a.clipTo(b);
  76426. b.clipTo(a);
  76427. a.build(b.allPolygons());
  76428. a.invert();
  76429. this.polygons = a.allPolygons();
  76430. };
  76431. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  76432. // not modified.
  76433. CSG.prototype.inverse = function () {
  76434. var csg = this.clone();
  76435. csg.inverseInPlace();
  76436. return csg;
  76437. };
  76438. CSG.prototype.inverseInPlace = function () {
  76439. this.polygons.map(function (p) { p.flip(); });
  76440. };
  76441. // This is used to keep meshes transformations so they can be restored
  76442. // when we build back a Babylon Mesh
  76443. // NB : All CSG operations are performed in world coordinates
  76444. CSG.prototype.copyTransformAttributes = function (csg) {
  76445. this.matrix = csg.matrix;
  76446. this.position = csg.position;
  76447. this.rotation = csg.rotation;
  76448. this.scaling = csg.scaling;
  76449. this.rotationQuaternion = csg.rotationQuaternion;
  76450. return this;
  76451. };
  76452. // Build Raw mesh from CSG
  76453. // Coordinates here are in world space
  76454. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  76455. var matrix = this.matrix.clone();
  76456. matrix.invert();
  76457. 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;
  76458. if (keepSubMeshes) {
  76459. // Sort Polygons, since subMeshes are indices range
  76460. polygons.sort(function (a, b) {
  76461. if (a.shared.meshId === b.shared.meshId) {
  76462. return a.shared.subMeshId - b.shared.subMeshId;
  76463. }
  76464. else {
  76465. return a.shared.meshId - b.shared.meshId;
  76466. }
  76467. });
  76468. }
  76469. for (var i = 0, il = polygons.length; i < il; i++) {
  76470. polygon = polygons[i];
  76471. // Building SubMeshes
  76472. if (!subMesh_dict[polygon.shared.meshId]) {
  76473. subMesh_dict[polygon.shared.meshId] = {};
  76474. }
  76475. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  76476. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  76477. indexStart: +Infinity,
  76478. indexEnd: -Infinity,
  76479. materialIndex: polygon.shared.materialIndex
  76480. };
  76481. }
  76482. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  76483. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  76484. polygonIndices[0] = 0;
  76485. polygonIndices[1] = j - 1;
  76486. polygonIndices[2] = j;
  76487. for (var k = 0; k < 3; k++) {
  76488. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  76489. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  76490. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  76491. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  76492. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  76493. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  76494. // Check if 2 points can be merged
  76495. if (!(typeof vertex_idx !== 'undefined' &&
  76496. normals[vertex_idx * 3] === localNormal.x &&
  76497. normals[vertex_idx * 3 + 1] === localNormal.y &&
  76498. normals[vertex_idx * 3 + 2] === localNormal.z &&
  76499. uvs[vertex_idx * 2] === uv.x &&
  76500. uvs[vertex_idx * 2 + 1] === uv.y)) {
  76501. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  76502. uvs.push(uv.x, uv.y);
  76503. normals.push(normal.x, normal.y, normal.z);
  76504. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  76505. }
  76506. indices.push(vertex_idx);
  76507. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  76508. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  76509. currentIndex++;
  76510. }
  76511. }
  76512. }
  76513. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  76514. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  76515. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  76516. mesh.setIndices(indices, null);
  76517. if (keepSubMeshes) {
  76518. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  76519. var materialIndexOffset = 0, materialMaxIndex;
  76520. mesh.subMeshes = new Array();
  76521. for (var m in subMesh_dict) {
  76522. materialMaxIndex = -1;
  76523. for (var sm in subMesh_dict[m]) {
  76524. subMesh_obj = subMesh_dict[m][sm];
  76525. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  76526. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  76527. }
  76528. materialIndexOffset += ++materialMaxIndex;
  76529. }
  76530. }
  76531. return mesh;
  76532. };
  76533. // Build Mesh from CSG taking material and transforms into account
  76534. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  76535. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  76536. mesh.material = material;
  76537. mesh.position.copyFrom(this.position);
  76538. mesh.rotation.copyFrom(this.rotation);
  76539. if (this.rotationQuaternion) {
  76540. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  76541. }
  76542. mesh.scaling.copyFrom(this.scaling);
  76543. mesh.computeWorldMatrix(true);
  76544. return mesh;
  76545. };
  76546. return CSG;
  76547. }());
  76548. BABYLON.CSG = CSG;
  76549. })(BABYLON || (BABYLON = {}));
  76550. //# sourceMappingURL=babylon.csg.js.map
  76551. "use strict";
  76552. var BABYLON;
  76553. (function (BABYLON) {
  76554. var LensFlare = /** @class */ (function () {
  76555. function LensFlare(size, position, color, imgUrl, system) {
  76556. this.size = size;
  76557. this.position = position;
  76558. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  76559. this.color = color || new BABYLON.Color3(1, 1, 1);
  76560. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  76561. this._system = system;
  76562. system.lensFlares.push(this);
  76563. }
  76564. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  76565. return new LensFlare(size, position, color, imgUrl, system);
  76566. };
  76567. LensFlare.prototype.dispose = function () {
  76568. if (this.texture) {
  76569. this.texture.dispose();
  76570. }
  76571. // Remove from scene
  76572. var index = this._system.lensFlares.indexOf(this);
  76573. this._system.lensFlares.splice(index, 1);
  76574. };
  76575. ;
  76576. return LensFlare;
  76577. }());
  76578. BABYLON.LensFlare = LensFlare;
  76579. })(BABYLON || (BABYLON = {}));
  76580. //# sourceMappingURL=babylon.lensFlare.js.map
  76581. "use strict";
  76582. var BABYLON;
  76583. (function (BABYLON) {
  76584. var LensFlareSystem = /** @class */ (function () {
  76585. function LensFlareSystem(name, emitter, scene) {
  76586. this.name = name;
  76587. this.lensFlares = new Array();
  76588. this.borderLimit = 300;
  76589. this.viewportBorder = 0;
  76590. this.layerMask = 0x0FFFFFFF;
  76591. this._vertexBuffers = {};
  76592. this._isEnabled = true;
  76593. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76594. this._emitter = emitter;
  76595. this.id = name;
  76596. scene.lensFlareSystems.push(this);
  76597. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  76598. var engine = scene.getEngine();
  76599. // VBO
  76600. var vertices = [];
  76601. vertices.push(1, 1);
  76602. vertices.push(-1, 1);
  76603. vertices.push(-1, -1);
  76604. vertices.push(1, -1);
  76605. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76606. // Indices
  76607. var indices = [];
  76608. indices.push(0);
  76609. indices.push(1);
  76610. indices.push(2);
  76611. indices.push(0);
  76612. indices.push(2);
  76613. indices.push(3);
  76614. this._indexBuffer = engine.createIndexBuffer(indices);
  76615. // Effects
  76616. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  76617. }
  76618. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  76619. get: function () {
  76620. return this._isEnabled;
  76621. },
  76622. set: function (value) {
  76623. this._isEnabled = value;
  76624. },
  76625. enumerable: true,
  76626. configurable: true
  76627. });
  76628. LensFlareSystem.prototype.getScene = function () {
  76629. return this._scene;
  76630. };
  76631. LensFlareSystem.prototype.getEmitter = function () {
  76632. return this._emitter;
  76633. };
  76634. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  76635. this._emitter = newEmitter;
  76636. };
  76637. LensFlareSystem.prototype.getEmitterPosition = function () {
  76638. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  76639. };
  76640. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  76641. var position = this.getEmitterPosition();
  76642. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  76643. this._positionX = position.x;
  76644. this._positionY = position.y;
  76645. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  76646. if (this.viewportBorder > 0) {
  76647. globalViewport.x -= this.viewportBorder;
  76648. globalViewport.y -= this.viewportBorder;
  76649. globalViewport.width += this.viewportBorder * 2;
  76650. globalViewport.height += this.viewportBorder * 2;
  76651. position.x += this.viewportBorder;
  76652. position.y += this.viewportBorder;
  76653. this._positionX += this.viewportBorder;
  76654. this._positionY += this.viewportBorder;
  76655. }
  76656. if (position.z > 0) {
  76657. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  76658. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  76659. return true;
  76660. }
  76661. return true;
  76662. }
  76663. return false;
  76664. };
  76665. LensFlareSystem.prototype._isVisible = function () {
  76666. if (!this._isEnabled || !this._scene.activeCamera) {
  76667. return false;
  76668. }
  76669. var emitterPosition = this.getEmitterPosition();
  76670. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  76671. var distance = direction.length();
  76672. direction.normalize();
  76673. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  76674. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  76675. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  76676. };
  76677. LensFlareSystem.prototype.render = function () {
  76678. if (!this._effect.isReady() || !this._scene.activeCamera)
  76679. return false;
  76680. var engine = this._scene.getEngine();
  76681. var viewport = this._scene.activeCamera.viewport;
  76682. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  76683. // Position
  76684. if (!this.computeEffectivePosition(globalViewport)) {
  76685. return false;
  76686. }
  76687. // Visibility
  76688. if (!this._isVisible()) {
  76689. return false;
  76690. }
  76691. // Intensity
  76692. var awayX;
  76693. var awayY;
  76694. if (this._positionX < this.borderLimit + globalViewport.x) {
  76695. awayX = this.borderLimit + globalViewport.x - this._positionX;
  76696. }
  76697. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  76698. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  76699. }
  76700. else {
  76701. awayX = 0;
  76702. }
  76703. if (this._positionY < this.borderLimit + globalViewport.y) {
  76704. awayY = this.borderLimit + globalViewport.y - this._positionY;
  76705. }
  76706. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  76707. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  76708. }
  76709. else {
  76710. awayY = 0;
  76711. }
  76712. var away = (awayX > awayY) ? awayX : awayY;
  76713. away -= this.viewportBorder;
  76714. if (away > this.borderLimit) {
  76715. away = this.borderLimit;
  76716. }
  76717. var intensity = 1.0 - (away / this.borderLimit);
  76718. if (intensity < 0) {
  76719. return false;
  76720. }
  76721. if (intensity > 1.0) {
  76722. intensity = 1.0;
  76723. }
  76724. if (this.viewportBorder > 0) {
  76725. globalViewport.x += this.viewportBorder;
  76726. globalViewport.y += this.viewportBorder;
  76727. globalViewport.width -= this.viewportBorder * 2;
  76728. globalViewport.height -= this.viewportBorder * 2;
  76729. this._positionX -= this.viewportBorder;
  76730. this._positionY -= this.viewportBorder;
  76731. }
  76732. // Position
  76733. var centerX = globalViewport.x + globalViewport.width / 2;
  76734. var centerY = globalViewport.y + globalViewport.height / 2;
  76735. var distX = centerX - this._positionX;
  76736. var distY = centerY - this._positionY;
  76737. // Effects
  76738. engine.enableEffect(this._effect);
  76739. engine.setState(false);
  76740. engine.setDepthBuffer(false);
  76741. // VBOs
  76742. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76743. // Flares
  76744. for (var index = 0; index < this.lensFlares.length; index++) {
  76745. var flare = this.lensFlares[index];
  76746. engine.setAlphaMode(flare.alphaMode);
  76747. var x = centerX - (distX * flare.position);
  76748. var y = centerY - (distY * flare.position);
  76749. var cw = flare.size;
  76750. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  76751. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  76752. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  76753. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  76754. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  76755. // Texture
  76756. this._effect.setTexture("textureSampler", flare.texture);
  76757. // Color
  76758. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  76759. // Draw order
  76760. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76761. }
  76762. engine.setDepthBuffer(true);
  76763. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76764. return true;
  76765. };
  76766. LensFlareSystem.prototype.dispose = function () {
  76767. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76768. if (vertexBuffer) {
  76769. vertexBuffer.dispose();
  76770. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76771. }
  76772. if (this._indexBuffer) {
  76773. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76774. this._indexBuffer = null;
  76775. }
  76776. while (this.lensFlares.length) {
  76777. this.lensFlares[0].dispose();
  76778. }
  76779. // Remove from scene
  76780. var index = this._scene.lensFlareSystems.indexOf(this);
  76781. this._scene.lensFlareSystems.splice(index, 1);
  76782. };
  76783. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  76784. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  76785. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  76786. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  76787. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  76788. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  76789. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  76790. var parsedFlare = parsedLensFlareSystem.flares[index];
  76791. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  76792. }
  76793. return lensFlareSystem;
  76794. };
  76795. LensFlareSystem.prototype.serialize = function () {
  76796. var serializationObject = {};
  76797. serializationObject.id = this.id;
  76798. serializationObject.name = this.name;
  76799. serializationObject.emitterId = this.getEmitter().id;
  76800. serializationObject.borderLimit = this.borderLimit;
  76801. serializationObject.flares = [];
  76802. for (var index = 0; index < this.lensFlares.length; index++) {
  76803. var flare = this.lensFlares[index];
  76804. serializationObject.flares.push({
  76805. size: flare.size,
  76806. position: flare.position,
  76807. color: flare.color.asArray(),
  76808. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  76809. });
  76810. }
  76811. return serializationObject;
  76812. };
  76813. return LensFlareSystem;
  76814. }());
  76815. BABYLON.LensFlareSystem = LensFlareSystem;
  76816. })(BABYLON || (BABYLON = {}));
  76817. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  76818. "use strict";
  76819. var BABYLON;
  76820. (function (BABYLON) {
  76821. /**
  76822. * This is a holder class for the physics joint created by the physics plugin.
  76823. * It holds a set of functions to control the underlying joint.
  76824. */
  76825. var PhysicsJoint = /** @class */ (function () {
  76826. function PhysicsJoint(type, jointData) {
  76827. this.type = type;
  76828. this.jointData = jointData;
  76829. jointData.nativeParams = jointData.nativeParams || {};
  76830. }
  76831. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  76832. get: function () {
  76833. return this._physicsJoint;
  76834. },
  76835. set: function (newJoint) {
  76836. if (this._physicsJoint) {
  76837. //remove from the wolrd
  76838. }
  76839. this._physicsJoint = newJoint;
  76840. },
  76841. enumerable: true,
  76842. configurable: true
  76843. });
  76844. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  76845. set: function (physicsPlugin) {
  76846. this._physicsPlugin = physicsPlugin;
  76847. },
  76848. enumerable: true,
  76849. configurable: true
  76850. });
  76851. /**
  76852. * Execute a function that is physics-plugin specific.
  76853. * @param {Function} func the function that will be executed.
  76854. * It accepts two parameters: the physics world and the physics joint.
  76855. */
  76856. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  76857. func(this._physicsPlugin.world, this._physicsJoint);
  76858. };
  76859. //TODO check if the native joints are the same
  76860. //Joint Types
  76861. PhysicsJoint.DistanceJoint = 0;
  76862. PhysicsJoint.HingeJoint = 1;
  76863. PhysicsJoint.BallAndSocketJoint = 2;
  76864. PhysicsJoint.WheelJoint = 3;
  76865. PhysicsJoint.SliderJoint = 4;
  76866. //OIMO
  76867. PhysicsJoint.PrismaticJoint = 5;
  76868. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  76869. PhysicsJoint.UniversalJoint = 6;
  76870. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  76871. //Cannon
  76872. //Similar to a Ball-Joint. Different in params
  76873. PhysicsJoint.PointToPointJoint = 8;
  76874. //Cannon only at the moment
  76875. PhysicsJoint.SpringJoint = 9;
  76876. PhysicsJoint.LockJoint = 10;
  76877. return PhysicsJoint;
  76878. }());
  76879. BABYLON.PhysicsJoint = PhysicsJoint;
  76880. /**
  76881. * A class representing a physics distance joint.
  76882. */
  76883. var DistanceJoint = /** @class */ (function (_super) {
  76884. __extends(DistanceJoint, _super);
  76885. function DistanceJoint(jointData) {
  76886. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  76887. }
  76888. /**
  76889. * Update the predefined distance.
  76890. */
  76891. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  76892. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  76893. };
  76894. return DistanceJoint;
  76895. }(PhysicsJoint));
  76896. BABYLON.DistanceJoint = DistanceJoint;
  76897. var MotorEnabledJoint = /** @class */ (function (_super) {
  76898. __extends(MotorEnabledJoint, _super);
  76899. function MotorEnabledJoint(type, jointData) {
  76900. return _super.call(this, type, jointData) || this;
  76901. }
  76902. /**
  76903. * Set the motor values.
  76904. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76905. * @param {number} force the force to apply
  76906. * @param {number} maxForce max force for this motor.
  76907. */
  76908. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  76909. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76910. };
  76911. /**
  76912. * Set the motor's limits.
  76913. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76914. */
  76915. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76916. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76917. };
  76918. return MotorEnabledJoint;
  76919. }(PhysicsJoint));
  76920. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  76921. /**
  76922. * This class represents a single hinge physics joint
  76923. */
  76924. var HingeJoint = /** @class */ (function (_super) {
  76925. __extends(HingeJoint, _super);
  76926. function HingeJoint(jointData) {
  76927. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  76928. }
  76929. /**
  76930. * Set the motor values.
  76931. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76932. * @param {number} force the force to apply
  76933. * @param {number} maxForce max force for this motor.
  76934. */
  76935. HingeJoint.prototype.setMotor = function (force, maxForce) {
  76936. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76937. };
  76938. /**
  76939. * Set the motor's limits.
  76940. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76941. */
  76942. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76943. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76944. };
  76945. return HingeJoint;
  76946. }(MotorEnabledJoint));
  76947. BABYLON.HingeJoint = HingeJoint;
  76948. /**
  76949. * This class represents a dual hinge physics joint (same as wheel joint)
  76950. */
  76951. var Hinge2Joint = /** @class */ (function (_super) {
  76952. __extends(Hinge2Joint, _super);
  76953. function Hinge2Joint(jointData) {
  76954. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  76955. }
  76956. /**
  76957. * Set the motor values.
  76958. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76959. * @param {number} force the force to apply
  76960. * @param {number} maxForce max force for this motor.
  76961. * @param {motorIndex} the motor's index, 0 or 1.
  76962. */
  76963. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  76964. if (motorIndex === void 0) { motorIndex = 0; }
  76965. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  76966. };
  76967. /**
  76968. * Set the motor limits.
  76969. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76970. * @param {number} upperLimit the upper limit
  76971. * @param {number} lowerLimit lower limit
  76972. * @param {motorIndex} the motor's index, 0 or 1.
  76973. */
  76974. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  76975. if (motorIndex === void 0) { motorIndex = 0; }
  76976. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  76977. };
  76978. return Hinge2Joint;
  76979. }(MotorEnabledJoint));
  76980. BABYLON.Hinge2Joint = Hinge2Joint;
  76981. })(BABYLON || (BABYLON = {}));
  76982. //# sourceMappingURL=babylon.physicsJoint.js.map
  76983. "use strict";
  76984. var BABYLON;
  76985. (function (BABYLON) {
  76986. var PhysicsImpostor = /** @class */ (function () {
  76987. function PhysicsImpostor(object, type, _options, _scene) {
  76988. if (_options === void 0) { _options = { mass: 0 }; }
  76989. var _this = this;
  76990. this.object = object;
  76991. this.type = type;
  76992. this._options = _options;
  76993. this._scene = _scene;
  76994. this._bodyUpdateRequired = false;
  76995. this._onBeforePhysicsStepCallbacks = new Array();
  76996. this._onAfterPhysicsStepCallbacks = new Array();
  76997. this._onPhysicsCollideCallbacks = [];
  76998. this._deltaPosition = BABYLON.Vector3.Zero();
  76999. this._isDisposed = false;
  77000. //temp variables for parent rotation calculations
  77001. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  77002. this._tmpQuat = new BABYLON.Quaternion();
  77003. this._tmpQuat2 = new BABYLON.Quaternion();
  77004. /**
  77005. * this function is executed by the physics engine.
  77006. */
  77007. this.beforeStep = function () {
  77008. if (!_this._physicsEngine) {
  77009. return;
  77010. }
  77011. _this.object.translate(_this._deltaPosition, -1);
  77012. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  77013. _this.object.computeWorldMatrix(false);
  77014. if (_this.object.parent && _this.object.rotationQuaternion) {
  77015. _this.getParentsRotation();
  77016. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  77017. }
  77018. else {
  77019. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  77020. }
  77021. if (!_this._options.disableBidirectionalTransformation) {
  77022. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  77023. }
  77024. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  77025. func(_this);
  77026. });
  77027. };
  77028. /**
  77029. * this function is executed by the physics engine.
  77030. */
  77031. this.afterStep = function () {
  77032. if (!_this._physicsEngine) {
  77033. return;
  77034. }
  77035. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  77036. func(_this);
  77037. });
  77038. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  77039. // object has now its world rotation. needs to be converted to local.
  77040. if (_this.object.parent && _this.object.rotationQuaternion) {
  77041. _this.getParentsRotation();
  77042. _this._tmpQuat.conjugateInPlace();
  77043. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  77044. }
  77045. // take the position set and make it the absolute position of this object.
  77046. _this.object.setAbsolutePosition(_this.object.position);
  77047. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  77048. _this.object.translate(_this._deltaPosition, 1);
  77049. };
  77050. /**
  77051. * Legacy collision detection event support
  77052. */
  77053. this.onCollideEvent = null;
  77054. //event and body object due to cannon's event-based architecture.
  77055. this.onCollide = function (e) {
  77056. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  77057. return;
  77058. }
  77059. if (!_this._physicsEngine) {
  77060. return;
  77061. }
  77062. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  77063. if (otherImpostor) {
  77064. // Legacy collision detection event support
  77065. if (_this.onCollideEvent) {
  77066. _this.onCollideEvent(_this, otherImpostor);
  77067. }
  77068. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  77069. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  77070. }).forEach(function (obj) {
  77071. obj.callback(_this, otherImpostor);
  77072. });
  77073. }
  77074. };
  77075. //sanity check!
  77076. if (!this.object) {
  77077. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  77078. return;
  77079. }
  77080. //legacy support for old syntax.
  77081. if (!this._scene && object.getScene) {
  77082. this._scene = object.getScene();
  77083. }
  77084. if (!this._scene) {
  77085. return;
  77086. }
  77087. this._physicsEngine = this._scene.getPhysicsEngine();
  77088. if (!this._physicsEngine) {
  77089. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  77090. }
  77091. else {
  77092. //set the object's quaternion, if not set
  77093. if (!this.object.rotationQuaternion) {
  77094. if (this.object.rotation) {
  77095. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  77096. }
  77097. else {
  77098. this.object.rotationQuaternion = new BABYLON.Quaternion();
  77099. }
  77100. }
  77101. //default options params
  77102. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  77103. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  77104. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  77105. this._joints = [];
  77106. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  77107. if (!this.object.parent || this._options.ignoreParent) {
  77108. this._init();
  77109. }
  77110. else if (this.object.parent.physicsImpostor) {
  77111. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  77112. }
  77113. }
  77114. }
  77115. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  77116. get: function () {
  77117. return this._isDisposed;
  77118. },
  77119. enumerable: true,
  77120. configurable: true
  77121. });
  77122. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  77123. get: function () {
  77124. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  77125. },
  77126. set: function (value) {
  77127. this.setMass(value);
  77128. },
  77129. enumerable: true,
  77130. configurable: true
  77131. });
  77132. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  77133. get: function () {
  77134. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  77135. },
  77136. set: function (value) {
  77137. if (!this._physicsEngine) {
  77138. return;
  77139. }
  77140. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  77141. },
  77142. enumerable: true,
  77143. configurable: true
  77144. });
  77145. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  77146. get: function () {
  77147. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  77148. },
  77149. set: function (value) {
  77150. if (!this._physicsEngine) {
  77151. return;
  77152. }
  77153. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  77154. },
  77155. enumerable: true,
  77156. configurable: true
  77157. });
  77158. /**
  77159. * This function will completly initialize this impostor.
  77160. * It will create a new body - but only if this mesh has no parent.
  77161. * If it has, this impostor will not be used other than to define the impostor
  77162. * of the child mesh.
  77163. */
  77164. PhysicsImpostor.prototype._init = function () {
  77165. if (!this._physicsEngine) {
  77166. return;
  77167. }
  77168. this._physicsEngine.removeImpostor(this);
  77169. this.physicsBody = null;
  77170. this._parent = this._parent || this._getPhysicsParent();
  77171. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  77172. this._physicsEngine.addImpostor(this);
  77173. }
  77174. };
  77175. PhysicsImpostor.prototype._getPhysicsParent = function () {
  77176. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  77177. var parentMesh = this.object.parent;
  77178. return parentMesh.physicsImpostor;
  77179. }
  77180. return null;
  77181. };
  77182. /**
  77183. * Should a new body be generated.
  77184. */
  77185. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  77186. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  77187. };
  77188. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  77189. this.forceUpdate();
  77190. };
  77191. /**
  77192. * Force a regeneration of this or the parent's impostor's body.
  77193. * Use under cautious - This will remove all joints already implemented.
  77194. */
  77195. PhysicsImpostor.prototype.forceUpdate = function () {
  77196. this._init();
  77197. if (this.parent && !this._options.ignoreParent) {
  77198. this.parent.forceUpdate();
  77199. }
  77200. };
  77201. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  77202. /*public get mesh(): AbstractMesh {
  77203. return this._mesh;
  77204. }*/
  77205. /**
  77206. * Gets the body that holds this impostor. Either its own, or its parent.
  77207. */
  77208. get: function () {
  77209. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  77210. },
  77211. /**
  77212. * Set the physics body. Used mainly by the physics engine/plugin
  77213. */
  77214. set: function (physicsBody) {
  77215. if (this._physicsBody && this._physicsEngine) {
  77216. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  77217. }
  77218. this._physicsBody = physicsBody;
  77219. this.resetUpdateFlags();
  77220. },
  77221. enumerable: true,
  77222. configurable: true
  77223. });
  77224. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  77225. get: function () {
  77226. return !this._options.ignoreParent && this._parent ? this._parent : null;
  77227. },
  77228. set: function (value) {
  77229. this._parent = value;
  77230. },
  77231. enumerable: true,
  77232. configurable: true
  77233. });
  77234. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  77235. this._bodyUpdateRequired = false;
  77236. };
  77237. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  77238. if (this.object.getBoundingInfo) {
  77239. var q = this.object.rotationQuaternion;
  77240. //reset rotation
  77241. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  77242. //calculate the world matrix with no rotation
  77243. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77244. var boundingInfo = this.object.getBoundingInfo();
  77245. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  77246. //bring back the rotation
  77247. this.object.rotationQuaternion = q;
  77248. //calculate the world matrix with the new rotation
  77249. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77250. return size;
  77251. }
  77252. else {
  77253. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  77254. }
  77255. };
  77256. PhysicsImpostor.prototype.getObjectCenter = function () {
  77257. if (this.object.getBoundingInfo) {
  77258. var boundingInfo = this.object.getBoundingInfo();
  77259. return boundingInfo.boundingBox.centerWorld;
  77260. }
  77261. else {
  77262. return this.object.position;
  77263. }
  77264. };
  77265. /**
  77266. * Get a specific parametes from the options parameter.
  77267. */
  77268. PhysicsImpostor.prototype.getParam = function (paramName) {
  77269. return this._options[paramName];
  77270. };
  77271. /**
  77272. * Sets a specific parameter in the options given to the physics plugin
  77273. */
  77274. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  77275. this._options[paramName] = value;
  77276. this._bodyUpdateRequired = true;
  77277. };
  77278. /**
  77279. * Specifically change the body's mass option. Won't recreate the physics body object
  77280. */
  77281. PhysicsImpostor.prototype.setMass = function (mass) {
  77282. if (this.getParam("mass") !== mass) {
  77283. this.setParam("mass", mass);
  77284. }
  77285. if (this._physicsEngine) {
  77286. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  77287. }
  77288. };
  77289. PhysicsImpostor.prototype.getLinearVelocity = function () {
  77290. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  77291. };
  77292. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  77293. if (this._physicsEngine) {
  77294. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  77295. }
  77296. };
  77297. PhysicsImpostor.prototype.getAngularVelocity = function () {
  77298. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  77299. };
  77300. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  77301. if (this._physicsEngine) {
  77302. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  77303. }
  77304. };
  77305. /**
  77306. * Execute a function with the physics plugin native code.
  77307. * Provide a function the will have two variables - the world object and the physics body object.
  77308. */
  77309. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  77310. if (this._physicsEngine) {
  77311. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  77312. }
  77313. };
  77314. /**
  77315. * Register a function that will be executed before the physics world is stepping forward.
  77316. */
  77317. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  77318. this._onBeforePhysicsStepCallbacks.push(func);
  77319. };
  77320. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  77321. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  77322. if (index > -1) {
  77323. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  77324. }
  77325. else {
  77326. BABYLON.Tools.Warn("Function to remove was not found");
  77327. }
  77328. };
  77329. /**
  77330. * Register a function that will be executed after the physics step
  77331. */
  77332. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  77333. this._onAfterPhysicsStepCallbacks.push(func);
  77334. };
  77335. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  77336. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  77337. if (index > -1) {
  77338. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  77339. }
  77340. else {
  77341. BABYLON.Tools.Warn("Function to remove was not found");
  77342. }
  77343. };
  77344. /**
  77345. * register a function that will be executed when this impostor collides against a different body.
  77346. */
  77347. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  77348. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77349. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  77350. };
  77351. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  77352. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77353. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  77354. if (index > -1) {
  77355. this._onPhysicsCollideCallbacks.splice(index, 1);
  77356. }
  77357. else {
  77358. BABYLON.Tools.Warn("Function to remove was not found");
  77359. }
  77360. };
  77361. PhysicsImpostor.prototype.getParentsRotation = function () {
  77362. var parent = this.object.parent;
  77363. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  77364. while (parent) {
  77365. if (parent.rotationQuaternion) {
  77366. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  77367. }
  77368. else {
  77369. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  77370. }
  77371. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  77372. parent = parent.parent;
  77373. }
  77374. return this._tmpQuat;
  77375. };
  77376. /**
  77377. * Apply a force
  77378. */
  77379. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  77380. if (this._physicsEngine) {
  77381. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  77382. }
  77383. return this;
  77384. };
  77385. /**
  77386. * Apply an impulse
  77387. */
  77388. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  77389. if (this._physicsEngine) {
  77390. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  77391. }
  77392. return this;
  77393. };
  77394. /**
  77395. * A help function to create a joint.
  77396. */
  77397. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  77398. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  77399. this.addJoint(otherImpostor, joint);
  77400. return this;
  77401. };
  77402. /**
  77403. * Add a joint to this impostor with a different impostor.
  77404. */
  77405. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  77406. this._joints.push({
  77407. otherImpostor: otherImpostor,
  77408. joint: joint
  77409. });
  77410. if (this._physicsEngine) {
  77411. this._physicsEngine.addJoint(this, otherImpostor, joint);
  77412. }
  77413. return this;
  77414. };
  77415. /**
  77416. * Will keep this body still, in a sleep mode.
  77417. */
  77418. PhysicsImpostor.prototype.sleep = function () {
  77419. if (this._physicsEngine) {
  77420. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  77421. }
  77422. return this;
  77423. };
  77424. /**
  77425. * Wake the body up.
  77426. */
  77427. PhysicsImpostor.prototype.wakeUp = function () {
  77428. if (this._physicsEngine) {
  77429. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  77430. }
  77431. return this;
  77432. };
  77433. PhysicsImpostor.prototype.clone = function (newObject) {
  77434. if (!newObject)
  77435. return null;
  77436. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  77437. };
  77438. PhysicsImpostor.prototype.dispose = function () {
  77439. var _this = this;
  77440. //no dispose if no physics engine is available.
  77441. if (!this._physicsEngine) {
  77442. return;
  77443. }
  77444. this._joints.forEach(function (j) {
  77445. if (_this._physicsEngine) {
  77446. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  77447. }
  77448. });
  77449. //dispose the physics body
  77450. this._physicsEngine.removeImpostor(this);
  77451. if (this.parent) {
  77452. this.parent.forceUpdate();
  77453. }
  77454. else {
  77455. /*this._object.getChildMeshes().forEach(function(mesh) {
  77456. if (mesh.physicsImpostor) {
  77457. if (disposeChildren) {
  77458. mesh.physicsImpostor.dispose();
  77459. mesh.physicsImpostor = null;
  77460. }
  77461. }
  77462. })*/
  77463. }
  77464. this._isDisposed = true;
  77465. };
  77466. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  77467. this._deltaPosition.copyFrom(position);
  77468. };
  77469. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  77470. if (!this._deltaRotation) {
  77471. this._deltaRotation = new BABYLON.Quaternion();
  77472. }
  77473. this._deltaRotation.copyFrom(rotation);
  77474. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  77475. };
  77476. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  77477. if (this._physicsEngine) {
  77478. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  77479. }
  77480. return this;
  77481. };
  77482. PhysicsImpostor.prototype.getRadius = function () {
  77483. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  77484. };
  77485. /**
  77486. * Sync a bone with this impostor
  77487. * @param bone The bone to sync to the impostor.
  77488. * @param boneMesh The mesh that the bone is influencing.
  77489. * @param jointPivot The pivot of the joint / bone in local space.
  77490. * @param distToJoint Optional distance from the impostor to the joint.
  77491. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77492. */
  77493. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  77494. var tempVec = PhysicsImpostor._tmpVecs[0];
  77495. var mesh = this.object;
  77496. if (mesh.rotationQuaternion) {
  77497. if (adjustRotation) {
  77498. var tempQuat = PhysicsImpostor._tmpQuat;
  77499. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  77500. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  77501. }
  77502. else {
  77503. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  77504. }
  77505. }
  77506. tempVec.x = 0;
  77507. tempVec.y = 0;
  77508. tempVec.z = 0;
  77509. if (jointPivot) {
  77510. tempVec.x = jointPivot.x;
  77511. tempVec.y = jointPivot.y;
  77512. tempVec.z = jointPivot.z;
  77513. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  77514. if (distToJoint === undefined || distToJoint === null) {
  77515. distToJoint = jointPivot.length();
  77516. }
  77517. tempVec.x *= distToJoint;
  77518. tempVec.y *= distToJoint;
  77519. tempVec.z *= distToJoint;
  77520. }
  77521. if (bone.getParent()) {
  77522. tempVec.addInPlace(mesh.getAbsolutePosition());
  77523. bone.setAbsolutePosition(tempVec, boneMesh);
  77524. }
  77525. else {
  77526. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  77527. boneMesh.position.x -= tempVec.x;
  77528. boneMesh.position.y -= tempVec.y;
  77529. boneMesh.position.z -= tempVec.z;
  77530. }
  77531. };
  77532. /**
  77533. * Sync impostor to a bone
  77534. * @param bone The bone that the impostor will be synced to.
  77535. * @param boneMesh The mesh that the bone is influencing.
  77536. * @param jointPivot The pivot of the joint / bone in local space.
  77537. * @param distToJoint Optional distance from the impostor to the joint.
  77538. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77539. * @param boneAxis Optional vector3 axis the bone is aligned with
  77540. */
  77541. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  77542. var mesh = this.object;
  77543. if (mesh.rotationQuaternion) {
  77544. if (adjustRotation) {
  77545. var tempQuat = PhysicsImpostor._tmpQuat;
  77546. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  77547. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  77548. }
  77549. else {
  77550. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  77551. }
  77552. }
  77553. var pos = PhysicsImpostor._tmpVecs[0];
  77554. var boneDir = PhysicsImpostor._tmpVecs[1];
  77555. if (!boneAxis) {
  77556. boneAxis = PhysicsImpostor._tmpVecs[2];
  77557. boneAxis.x = 0;
  77558. boneAxis.y = 1;
  77559. boneAxis.z = 0;
  77560. }
  77561. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  77562. bone.getAbsolutePositionToRef(boneMesh, pos);
  77563. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  77564. distToJoint = jointPivot.length();
  77565. }
  77566. if (distToJoint !== undefined && distToJoint !== null) {
  77567. pos.x += boneDir.x * distToJoint;
  77568. pos.y += boneDir.y * distToJoint;
  77569. pos.z += boneDir.z * distToJoint;
  77570. }
  77571. mesh.setAbsolutePosition(pos);
  77572. };
  77573. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  77574. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  77575. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77576. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  77577. //Impostor types
  77578. PhysicsImpostor.NoImpostor = 0;
  77579. PhysicsImpostor.SphereImpostor = 1;
  77580. PhysicsImpostor.BoxImpostor = 2;
  77581. PhysicsImpostor.PlaneImpostor = 3;
  77582. PhysicsImpostor.MeshImpostor = 4;
  77583. PhysicsImpostor.CylinderImpostor = 7;
  77584. PhysicsImpostor.ParticleImpostor = 8;
  77585. PhysicsImpostor.HeightmapImpostor = 9;
  77586. return PhysicsImpostor;
  77587. }());
  77588. BABYLON.PhysicsImpostor = PhysicsImpostor;
  77589. })(BABYLON || (BABYLON = {}));
  77590. //# sourceMappingURL=babylon.physicsImpostor.js.map
  77591. "use strict";
  77592. var BABYLON;
  77593. (function (BABYLON) {
  77594. var PhysicsEngine = /** @class */ (function () {
  77595. function PhysicsEngine(gravity, _physicsPlugin) {
  77596. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  77597. this._physicsPlugin = _physicsPlugin;
  77598. //new methods and parameters
  77599. this._impostors = [];
  77600. this._joints = [];
  77601. if (!this._physicsPlugin.isSupported()) {
  77602. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  77603. + "Please make sure it is included.");
  77604. }
  77605. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  77606. this.setGravity(gravity);
  77607. this.setTimeStep();
  77608. }
  77609. PhysicsEngine.prototype.setGravity = function (gravity) {
  77610. this.gravity = gravity;
  77611. this._physicsPlugin.setGravity(this.gravity);
  77612. };
  77613. /**
  77614. * Set the time step of the physics engine.
  77615. * default is 1/60.
  77616. * To slow it down, enter 1/600 for example.
  77617. * To speed it up, 1/30
  77618. * @param {number} newTimeStep the new timestep to apply to this world.
  77619. */
  77620. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  77621. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  77622. this._physicsPlugin.setTimeStep(newTimeStep);
  77623. };
  77624. /**
  77625. * Get the time step of the physics engine.
  77626. */
  77627. PhysicsEngine.prototype.getTimeStep = function () {
  77628. return this._physicsPlugin.getTimeStep();
  77629. };
  77630. PhysicsEngine.prototype.dispose = function () {
  77631. this._impostors.forEach(function (impostor) {
  77632. impostor.dispose();
  77633. });
  77634. this._physicsPlugin.dispose();
  77635. };
  77636. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  77637. return this._physicsPlugin.name;
  77638. };
  77639. /**
  77640. * Adding a new impostor for the impostor tracking.
  77641. * This will be done by the impostor itself.
  77642. * @param {PhysicsImpostor} impostor the impostor to add
  77643. */
  77644. PhysicsEngine.prototype.addImpostor = function (impostor) {
  77645. impostor.uniqueId = this._impostors.push(impostor);
  77646. //if no parent, generate the body
  77647. if (!impostor.parent) {
  77648. this._physicsPlugin.generatePhysicsBody(impostor);
  77649. }
  77650. };
  77651. /**
  77652. * Remove an impostor from the engine.
  77653. * This impostor and its mesh will not longer be updated by the physics engine.
  77654. * @param {PhysicsImpostor} impostor the impostor to remove
  77655. */
  77656. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  77657. var index = this._impostors.indexOf(impostor);
  77658. if (index > -1) {
  77659. var removed = this._impostors.splice(index, 1);
  77660. //Is it needed?
  77661. if (removed.length) {
  77662. //this will also remove it from the world.
  77663. removed[0].physicsBody = null;
  77664. }
  77665. }
  77666. };
  77667. /**
  77668. * Add a joint to the physics engine
  77669. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  77670. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  77671. * @param {PhysicsJoint} the joint that will connect both impostors.
  77672. */
  77673. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  77674. var impostorJoint = {
  77675. mainImpostor: mainImpostor,
  77676. connectedImpostor: connectedImpostor,
  77677. joint: joint
  77678. };
  77679. joint.physicsPlugin = this._physicsPlugin;
  77680. this._joints.push(impostorJoint);
  77681. this._physicsPlugin.generateJoint(impostorJoint);
  77682. };
  77683. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  77684. var matchingJoints = this._joints.filter(function (impostorJoint) {
  77685. return (impostorJoint.connectedImpostor === connectedImpostor
  77686. && impostorJoint.joint === joint
  77687. && impostorJoint.mainImpostor === mainImpostor);
  77688. });
  77689. if (matchingJoints.length) {
  77690. this._physicsPlugin.removeJoint(matchingJoints[0]);
  77691. //TODO remove it from the list as well
  77692. }
  77693. };
  77694. /**
  77695. * Called by the scene. no need to call it.
  77696. */
  77697. PhysicsEngine.prototype._step = function (delta) {
  77698. var _this = this;
  77699. //check if any mesh has no body / requires an update
  77700. this._impostors.forEach(function (impostor) {
  77701. if (impostor.isBodyInitRequired()) {
  77702. _this._physicsPlugin.generatePhysicsBody(impostor);
  77703. }
  77704. });
  77705. if (delta > 0.1) {
  77706. delta = 0.1;
  77707. }
  77708. else if (delta <= 0) {
  77709. delta = 1.0 / 60.0;
  77710. }
  77711. this._physicsPlugin.executeStep(delta, this._impostors);
  77712. };
  77713. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  77714. return this._physicsPlugin;
  77715. };
  77716. PhysicsEngine.prototype.getImpostors = function () {
  77717. return this._impostors;
  77718. };
  77719. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  77720. for (var i = 0; i < this._impostors.length; ++i) {
  77721. if (this._impostors[i].object === object) {
  77722. return this._impostors[i];
  77723. }
  77724. }
  77725. return null;
  77726. };
  77727. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  77728. for (var i = 0; i < this._impostors.length; ++i) {
  77729. if (this._impostors[i].physicsBody === body) {
  77730. return this._impostors[i];
  77731. }
  77732. }
  77733. return null;
  77734. };
  77735. // Statics
  77736. PhysicsEngine.Epsilon = 0.001;
  77737. return PhysicsEngine;
  77738. }());
  77739. BABYLON.PhysicsEngine = PhysicsEngine;
  77740. })(BABYLON || (BABYLON = {}));
  77741. //# sourceMappingURL=babylon.physicsEngine.js.map
  77742. "use strict";
  77743. var BABYLON;
  77744. (function (BABYLON) {
  77745. var PhysicsHelper = /** @class */ (function () {
  77746. function PhysicsHelper(scene) {
  77747. this._scene = scene;
  77748. this._physicsEngine = this._scene.getPhysicsEngine();
  77749. if (!this._physicsEngine) {
  77750. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  77751. }
  77752. }
  77753. /**
  77754. * @param {Vector3} origin the origin of the explosion
  77755. * @param {number} radius the explosion radius
  77756. * @param {number} strength the explosion strength
  77757. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77758. */
  77759. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  77760. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77761. if (!this._physicsEngine) {
  77762. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  77763. return null;
  77764. }
  77765. var impostors = this._physicsEngine.getImpostors();
  77766. if (impostors.length === 0) {
  77767. return null;
  77768. }
  77769. var event = new PhysicsRadialExplosionEvent(this._scene);
  77770. impostors.forEach(function (impostor) {
  77771. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77772. if (!impostorForceAndContactPoint) {
  77773. return;
  77774. }
  77775. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77776. });
  77777. event.dispose(false);
  77778. return event;
  77779. };
  77780. /**
  77781. * @param {Vector3} origin the origin of the explosion
  77782. * @param {number} radius the explosion radius
  77783. * @param {number} strength the explosion strength
  77784. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77785. */
  77786. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  77787. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77788. if (!this._physicsEngine) {
  77789. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77790. return null;
  77791. }
  77792. var impostors = this._physicsEngine.getImpostors();
  77793. if (impostors.length === 0) {
  77794. return null;
  77795. }
  77796. var event = new PhysicsRadialExplosionEvent(this._scene);
  77797. impostors.forEach(function (impostor) {
  77798. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77799. if (!impostorForceAndContactPoint) {
  77800. return;
  77801. }
  77802. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77803. });
  77804. event.dispose(false);
  77805. return event;
  77806. };
  77807. /**
  77808. * @param {Vector3} origin the origin of the explosion
  77809. * @param {number} radius the explosion radius
  77810. * @param {number} strength the explosion strength
  77811. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77812. */
  77813. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  77814. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77815. if (!this._physicsEngine) {
  77816. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77817. return null;
  77818. }
  77819. var impostors = this._physicsEngine.getImpostors();
  77820. if (impostors.length === 0) {
  77821. return null;
  77822. }
  77823. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  77824. event.dispose(false);
  77825. return event;
  77826. };
  77827. /**
  77828. * @param {Vector3} origin the origin of the updraft
  77829. * @param {number} radius the radius of the updraft
  77830. * @param {number} strength the strength of the updraft
  77831. * @param {number} height the height of the updraft
  77832. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  77833. */
  77834. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  77835. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  77836. if (!this._physicsEngine) {
  77837. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77838. return null;
  77839. }
  77840. if (this._physicsEngine.getImpostors().length === 0) {
  77841. return null;
  77842. }
  77843. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  77844. event.dispose(false);
  77845. return event;
  77846. };
  77847. /**
  77848. * @param {Vector3} origin the of the vortex
  77849. * @param {number} radius the radius of the vortex
  77850. * @param {number} strength the strength of the vortex
  77851. * @param {number} height the height of the vortex
  77852. */
  77853. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  77854. if (!this._physicsEngine) {
  77855. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77856. return null;
  77857. }
  77858. if (this._physicsEngine.getImpostors().length === 0) {
  77859. return null;
  77860. }
  77861. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  77862. event.dispose(false);
  77863. return event;
  77864. };
  77865. return PhysicsHelper;
  77866. }());
  77867. BABYLON.PhysicsHelper = PhysicsHelper;
  77868. /***** Radial explosion *****/
  77869. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  77870. function PhysicsRadialExplosionEvent(scene) {
  77871. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  77872. this._rays = [];
  77873. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  77874. this._scene = scene;
  77875. }
  77876. /**
  77877. * Returns the data related to the radial explosion event (sphere & rays).
  77878. * @returns {PhysicsRadialExplosionEventData}
  77879. */
  77880. PhysicsRadialExplosionEvent.prototype.getData = function () {
  77881. this._dataFetched = true;
  77882. return {
  77883. sphere: this._sphere,
  77884. rays: this._rays,
  77885. };
  77886. };
  77887. /**
  77888. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  77889. * @param impostor
  77890. * @param {Vector3} origin the origin of the explosion
  77891. * @param {number} radius the explosion radius
  77892. * @param {number} strength the explosion strength
  77893. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  77894. * @returns {Nullable<PhysicsForceAndContactPoint>}
  77895. */
  77896. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  77897. if (impostor.mass === 0) {
  77898. return null;
  77899. }
  77900. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  77901. return null;
  77902. }
  77903. if (impostor.object.getClassName() !== 'Mesh') {
  77904. return null;
  77905. }
  77906. var impostorObject = impostor.object;
  77907. var impostorObjectCenter = impostor.getObjectCenter();
  77908. var direction = impostorObjectCenter.subtract(origin);
  77909. var ray = new BABYLON.Ray(origin, direction, radius);
  77910. this._rays.push(ray);
  77911. var hit = ray.intersectsMesh(impostorObject);
  77912. var contactPoint = hit.pickedPoint;
  77913. if (!contactPoint) {
  77914. return null;
  77915. }
  77916. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  77917. if (distanceFromOrigin > radius) {
  77918. return null;
  77919. }
  77920. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  77921. ? strength
  77922. : strength * (1 - (distanceFromOrigin / radius));
  77923. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77924. return { force: force, contactPoint: contactPoint };
  77925. };
  77926. /**
  77927. * Disposes the sphere.
  77928. * @param {bolean} force
  77929. */
  77930. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  77931. var _this = this;
  77932. if (force === void 0) { force = true; }
  77933. if (force) {
  77934. this._sphere.dispose();
  77935. }
  77936. else {
  77937. setTimeout(function () {
  77938. if (!_this._dataFetched) {
  77939. _this._sphere.dispose();
  77940. }
  77941. }, 0);
  77942. }
  77943. };
  77944. /*** Helpers ***/
  77945. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  77946. if (!this._sphere) {
  77947. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  77948. this._sphere.isVisible = false;
  77949. }
  77950. };
  77951. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  77952. var impostorObject = impostor.object;
  77953. this._prepareSphere();
  77954. this._sphere.position = origin;
  77955. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  77956. this._sphere._updateBoundingInfo();
  77957. this._sphere.computeWorldMatrix(true);
  77958. return this._sphere.intersectsMesh(impostorObject, true);
  77959. };
  77960. return PhysicsRadialExplosionEvent;
  77961. }());
  77962. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  77963. /***** Gravitational Field *****/
  77964. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  77965. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  77966. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77967. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77968. this._physicsHelper = physicsHelper;
  77969. this._scene = scene;
  77970. this._origin = origin;
  77971. this._radius = radius;
  77972. this._strength = strength;
  77973. this._falloff = falloff;
  77974. this._tickCallback = this._tick.bind(this);
  77975. }
  77976. /**
  77977. * Returns the data related to the gravitational field event (sphere).
  77978. * @returns {PhysicsGravitationalFieldEventData}
  77979. */
  77980. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  77981. this._dataFetched = true;
  77982. return {
  77983. sphere: this._sphere,
  77984. };
  77985. };
  77986. /**
  77987. * Enables the gravitational field.
  77988. */
  77989. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  77990. this._tickCallback.call(this);
  77991. this._scene.registerBeforeRender(this._tickCallback);
  77992. };
  77993. /**
  77994. * Disables the gravitational field.
  77995. */
  77996. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  77997. this._scene.unregisterBeforeRender(this._tickCallback);
  77998. };
  77999. /**
  78000. * Disposes the sphere.
  78001. * @param {bolean} force
  78002. */
  78003. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  78004. var _this = this;
  78005. if (force === void 0) { force = true; }
  78006. if (force) {
  78007. this._sphere.dispose();
  78008. }
  78009. else {
  78010. setTimeout(function () {
  78011. if (!_this._dataFetched) {
  78012. _this._sphere.dispose();
  78013. }
  78014. }, 0);
  78015. }
  78016. };
  78017. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  78018. // Since the params won't change, we fetch the event only once
  78019. if (this._sphere) {
  78020. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78021. }
  78022. else {
  78023. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78024. if (radialExplosionEvent) {
  78025. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  78026. }
  78027. }
  78028. };
  78029. return PhysicsGravitationalFieldEvent;
  78030. }());
  78031. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  78032. /***** Updraft *****/
  78033. var PhysicsUpdraftEvent = /** @class */ (function () {
  78034. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  78035. this._scene = _scene;
  78036. this._origin = _origin;
  78037. this._radius = _radius;
  78038. this._strength = _strength;
  78039. this._height = _height;
  78040. this._updraftMode = _updraftMode;
  78041. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78042. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  78043. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78044. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78045. this._physicsEngine = this._scene.getPhysicsEngine();
  78046. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78047. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78048. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78049. this._originDirection = this._origin.subtract(this._originTop).normalize();
  78050. }
  78051. this._tickCallback = this._tick.bind(this);
  78052. }
  78053. /**
  78054. * Returns the data related to the updraft event (cylinder).
  78055. * @returns {PhysicsUpdraftEventData}
  78056. */
  78057. PhysicsUpdraftEvent.prototype.getData = function () {
  78058. this._dataFetched = true;
  78059. return {
  78060. cylinder: this._cylinder,
  78061. };
  78062. };
  78063. /**
  78064. * Enables the updraft.
  78065. */
  78066. PhysicsUpdraftEvent.prototype.enable = function () {
  78067. this._tickCallback.call(this);
  78068. this._scene.registerBeforeRender(this._tickCallback);
  78069. };
  78070. /**
  78071. * Disables the cortex.
  78072. */
  78073. PhysicsUpdraftEvent.prototype.disable = function () {
  78074. this._scene.unregisterBeforeRender(this._tickCallback);
  78075. };
  78076. /**
  78077. * Disposes the sphere.
  78078. * @param {bolean} force
  78079. */
  78080. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  78081. var _this = this;
  78082. if (force === void 0) { force = true; }
  78083. if (force) {
  78084. this._cylinder.dispose();
  78085. }
  78086. else {
  78087. setTimeout(function () {
  78088. if (!_this._dataFetched) {
  78089. _this._cylinder.dispose();
  78090. }
  78091. }, 0);
  78092. }
  78093. };
  78094. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78095. if (impostor.mass === 0) {
  78096. return null;
  78097. }
  78098. if (!this._intersectsWithCylinder(impostor)) {
  78099. return null;
  78100. }
  78101. var impostorObjectCenter = impostor.getObjectCenter();
  78102. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78103. var direction = this._originDirection;
  78104. }
  78105. else {
  78106. var direction = impostorObjectCenter.subtract(this._originTop);
  78107. }
  78108. var multiplier = this._strength * -1;
  78109. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78110. return { force: force, contactPoint: impostorObjectCenter };
  78111. };
  78112. PhysicsUpdraftEvent.prototype._tick = function () {
  78113. var _this = this;
  78114. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78115. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78116. if (!impostorForceAndContactPoint) {
  78117. return;
  78118. }
  78119. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78120. });
  78121. };
  78122. /*** Helpers ***/
  78123. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  78124. if (!this._cylinder) {
  78125. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  78126. height: this._height,
  78127. diameter: this._radius * 2,
  78128. }, this._scene);
  78129. this._cylinder.isVisible = false;
  78130. }
  78131. };
  78132. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  78133. var impostorObject = impostor.object;
  78134. this._prepareCylinder();
  78135. this._cylinder.position = this._cylinderPosition;
  78136. return this._cylinder.intersectsMesh(impostorObject, true);
  78137. };
  78138. return PhysicsUpdraftEvent;
  78139. }());
  78140. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  78141. /***** Vortex *****/
  78142. var PhysicsVortexEvent = /** @class */ (function () {
  78143. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  78144. this._scene = _scene;
  78145. this._origin = _origin;
  78146. this._radius = _radius;
  78147. this._strength = _strength;
  78148. this._height = _height;
  78149. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78150. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  78151. this._updraftMultiplier = 0.02;
  78152. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78153. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78154. this._physicsEngine = this._scene.getPhysicsEngine();
  78155. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78156. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78157. this._tickCallback = this._tick.bind(this);
  78158. }
  78159. /**
  78160. * Returns the data related to the vortex event (cylinder).
  78161. * @returns {PhysicsVortexEventData}
  78162. */
  78163. PhysicsVortexEvent.prototype.getData = function () {
  78164. this._dataFetched = true;
  78165. return {
  78166. cylinder: this._cylinder,
  78167. };
  78168. };
  78169. /**
  78170. * Enables the vortex.
  78171. */
  78172. PhysicsVortexEvent.prototype.enable = function () {
  78173. this._tickCallback.call(this);
  78174. this._scene.registerBeforeRender(this._tickCallback);
  78175. };
  78176. /**
  78177. * Disables the cortex.
  78178. */
  78179. PhysicsVortexEvent.prototype.disable = function () {
  78180. this._scene.unregisterBeforeRender(this._tickCallback);
  78181. };
  78182. /**
  78183. * Disposes the sphere.
  78184. * @param {bolean} force
  78185. */
  78186. PhysicsVortexEvent.prototype.dispose = function (force) {
  78187. var _this = this;
  78188. if (force === void 0) { force = true; }
  78189. if (force) {
  78190. this._cylinder.dispose();
  78191. }
  78192. else {
  78193. setTimeout(function () {
  78194. if (!_this._dataFetched) {
  78195. _this._cylinder.dispose();
  78196. }
  78197. }, 0);
  78198. }
  78199. };
  78200. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78201. if (impostor.mass === 0) {
  78202. return null;
  78203. }
  78204. if (!this._intersectsWithCylinder(impostor)) {
  78205. return null;
  78206. }
  78207. if (impostor.object.getClassName() !== 'Mesh') {
  78208. return null;
  78209. }
  78210. var impostorObject = impostor.object;
  78211. var impostorObjectCenter = impostor.getObjectCenter();
  78212. 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)
  78213. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  78214. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  78215. var hit = ray.intersectsMesh(impostorObject);
  78216. var contactPoint = hit.pickedPoint;
  78217. if (!contactPoint) {
  78218. return null;
  78219. }
  78220. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  78221. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  78222. var directionToOrigin = contactPoint.normalize();
  78223. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78224. directionToOrigin = directionToOrigin.negate();
  78225. }
  78226. // TODO: find a more physically based solution
  78227. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78228. var forceX = directionToOrigin.x * this._strength / 8;
  78229. var forceY = directionToOrigin.y * this._updraftMultiplier;
  78230. var forceZ = directionToOrigin.z * this._strength / 8;
  78231. }
  78232. else {
  78233. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  78234. var forceY = this._originTop.y * this._updraftMultiplier;
  78235. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  78236. }
  78237. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  78238. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  78239. return { force: force, contactPoint: impostorObjectCenter };
  78240. };
  78241. PhysicsVortexEvent.prototype._tick = function () {
  78242. var _this = this;
  78243. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78244. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78245. if (!impostorForceAndContactPoint) {
  78246. return;
  78247. }
  78248. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78249. });
  78250. };
  78251. /*** Helpers ***/
  78252. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  78253. if (!this._cylinder) {
  78254. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  78255. height: this._height,
  78256. diameter: this._radius * 2,
  78257. }, this._scene);
  78258. this._cylinder.isVisible = false;
  78259. }
  78260. };
  78261. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  78262. var impostorObject = impostor.object;
  78263. this._prepareCylinder();
  78264. this._cylinder.position = this._cylinderPosition;
  78265. return this._cylinder.intersectsMesh(impostorObject, true);
  78266. };
  78267. return PhysicsVortexEvent;
  78268. }());
  78269. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  78270. /***** Enums *****/
  78271. /**
  78272. * The strenght of the force in correspondence to the distance of the affected object
  78273. */
  78274. var PhysicsRadialImpulseFalloff;
  78275. (function (PhysicsRadialImpulseFalloff) {
  78276. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  78277. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  78278. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  78279. /**
  78280. * The strenght of the force in correspondence to the distance of the affected object
  78281. */
  78282. var PhysicsUpdraftMode;
  78283. (function (PhysicsUpdraftMode) {
  78284. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  78285. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  78286. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  78287. })(BABYLON || (BABYLON = {}));
  78288. //# sourceMappingURL=babylon.physicsHelper.js.map
  78289. "use strict";
  78290. var BABYLON;
  78291. (function (BABYLON) {
  78292. var CannonJSPlugin = /** @class */ (function () {
  78293. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  78294. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  78295. if (iterations === void 0) { iterations = 10; }
  78296. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  78297. this.name = "CannonJSPlugin";
  78298. this._physicsMaterials = new Array();
  78299. this._fixedTimeStep = 1 / 60;
  78300. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  78301. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  78302. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  78303. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  78304. this._tmpPosition = BABYLON.Vector3.Zero();
  78305. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  78306. this._tmpUnityRotation = new BABYLON.Quaternion();
  78307. if (!this.isSupported()) {
  78308. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  78309. return;
  78310. }
  78311. this._extendNamespace();
  78312. this.world = new this.BJSCANNON.World();
  78313. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  78314. this.world.solver.iterations = iterations;
  78315. }
  78316. CannonJSPlugin.prototype.setGravity = function (gravity) {
  78317. this.world.gravity.copy(gravity);
  78318. };
  78319. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  78320. this._fixedTimeStep = timeStep;
  78321. };
  78322. CannonJSPlugin.prototype.getTimeStep = function () {
  78323. return this._fixedTimeStep;
  78324. };
  78325. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  78326. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  78327. };
  78328. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78329. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78330. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78331. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  78332. };
  78333. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78334. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78335. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78336. impostor.physicsBody.applyForce(impulse, worldPoint);
  78337. };
  78338. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78339. //parent-child relationship. Does this impostor has a parent impostor?
  78340. if (impostor.parent) {
  78341. if (impostor.physicsBody) {
  78342. this.removePhysicsBody(impostor);
  78343. //TODO is that needed?
  78344. impostor.forceUpdate();
  78345. }
  78346. return;
  78347. }
  78348. //should a new body be created for this impostor?
  78349. if (impostor.isBodyInitRequired()) {
  78350. var shape = this._createShape(impostor);
  78351. //unregister events, if body is being changed
  78352. var oldBody = impostor.physicsBody;
  78353. if (oldBody) {
  78354. this.removePhysicsBody(impostor);
  78355. }
  78356. //create the body and material
  78357. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  78358. var bodyCreationObject = {
  78359. mass: impostor.getParam("mass"),
  78360. material: material
  78361. };
  78362. // A simple extend, in case native options were used.
  78363. var nativeOptions = impostor.getParam("nativeOptions");
  78364. for (var key in nativeOptions) {
  78365. if (nativeOptions.hasOwnProperty(key)) {
  78366. bodyCreationObject[key] = nativeOptions[key];
  78367. }
  78368. }
  78369. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  78370. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  78371. this.world.addEventListener("preStep", impostor.beforeStep);
  78372. this.world.addEventListener("postStep", impostor.afterStep);
  78373. impostor.physicsBody.addShape(shape);
  78374. this.world.add(impostor.physicsBody);
  78375. //try to keep the body moving in the right direction by taking old properties.
  78376. //Should be tested!
  78377. if (oldBody) {
  78378. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  78379. impostor.physicsBody[param].copy(oldBody[param]);
  78380. });
  78381. }
  78382. this._processChildMeshes(impostor);
  78383. }
  78384. //now update the body's transformation
  78385. this._updatePhysicsBodyTransformation(impostor);
  78386. };
  78387. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  78388. var _this = this;
  78389. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  78390. var currentRotation = mainImpostor.object.rotationQuaternion;
  78391. if (meshChildren.length) {
  78392. var processMesh = function (localPosition, mesh) {
  78393. if (!currentRotation || !mesh.rotationQuaternion) {
  78394. return;
  78395. }
  78396. var childImpostor = mesh.getPhysicsImpostor();
  78397. if (childImpostor) {
  78398. var parent = childImpostor.parent;
  78399. if (parent !== mainImpostor) {
  78400. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  78401. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  78402. if (childImpostor.physicsBody) {
  78403. _this.removePhysicsBody(childImpostor);
  78404. childImpostor.physicsBody = null;
  78405. }
  78406. childImpostor.parent = mainImpostor;
  78407. childImpostor.resetUpdateFlags();
  78408. 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));
  78409. //Add the mass of the children.
  78410. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  78411. }
  78412. }
  78413. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  78414. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  78415. };
  78416. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  78417. }
  78418. };
  78419. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78420. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  78421. this.world.removeEventListener("preStep", impostor.beforeStep);
  78422. this.world.removeEventListener("postStep", impostor.afterStep);
  78423. this.world.remove(impostor.physicsBody);
  78424. };
  78425. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78426. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78427. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78428. if (!mainBody || !connectedBody) {
  78429. return;
  78430. }
  78431. var constraint;
  78432. var jointData = impostorJoint.joint.jointData;
  78433. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  78434. var constraintData = {
  78435. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  78436. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  78437. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  78438. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  78439. maxForce: jointData.nativeParams.maxForce,
  78440. collideConnected: !!jointData.collision
  78441. };
  78442. switch (impostorJoint.joint.type) {
  78443. case BABYLON.PhysicsJoint.HingeJoint:
  78444. case BABYLON.PhysicsJoint.Hinge2Joint:
  78445. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  78446. break;
  78447. case BABYLON.PhysicsJoint.DistanceJoint:
  78448. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  78449. break;
  78450. case BABYLON.PhysicsJoint.SpringJoint:
  78451. var springData = jointData;
  78452. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  78453. restLength: springData.length,
  78454. stiffness: springData.stiffness,
  78455. damping: springData.damping,
  78456. localAnchorA: constraintData.pivotA,
  78457. localAnchorB: constraintData.pivotB
  78458. });
  78459. break;
  78460. case BABYLON.PhysicsJoint.LockJoint:
  78461. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  78462. break;
  78463. case BABYLON.PhysicsJoint.PointToPointJoint:
  78464. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78465. default:
  78466. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  78467. break;
  78468. }
  78469. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  78470. constraint.collideConnected = !!jointData.collision;
  78471. impostorJoint.joint.physicsJoint = constraint;
  78472. //don't add spring as constraint, as it is not one.
  78473. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  78474. this.world.addConstraint(constraint);
  78475. }
  78476. else {
  78477. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  78478. constraint.applyForce();
  78479. });
  78480. }
  78481. };
  78482. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78483. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  78484. };
  78485. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  78486. var index;
  78487. var mat;
  78488. for (index = 0; index < this._physicsMaterials.length; index++) {
  78489. mat = this._physicsMaterials[index];
  78490. if (mat.friction === friction && mat.restitution === restitution) {
  78491. return mat;
  78492. }
  78493. }
  78494. var currentMat = new this.BJSCANNON.Material(name);
  78495. currentMat.friction = friction;
  78496. currentMat.restitution = restitution;
  78497. this._physicsMaterials.push(currentMat);
  78498. return currentMat;
  78499. };
  78500. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  78501. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  78502. };
  78503. CannonJSPlugin.prototype._createShape = function (impostor) {
  78504. var object = impostor.object;
  78505. var returnValue;
  78506. var extendSize = impostor.getObjectExtendSize();
  78507. switch (impostor.type) {
  78508. case BABYLON.PhysicsImpostor.SphereImpostor:
  78509. var radiusX = extendSize.x;
  78510. var radiusY = extendSize.y;
  78511. var radiusZ = extendSize.z;
  78512. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  78513. break;
  78514. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  78515. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78516. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  78517. break;
  78518. case BABYLON.PhysicsImpostor.BoxImpostor:
  78519. var box = extendSize.scale(0.5);
  78520. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  78521. break;
  78522. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78523. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  78524. returnValue = new this.BJSCANNON.Plane();
  78525. break;
  78526. case BABYLON.PhysicsImpostor.MeshImpostor:
  78527. // should transform the vertex data to world coordinates!!
  78528. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  78529. var rawFaces = object.getIndices ? object.getIndices() : [];
  78530. if (!rawVerts)
  78531. return;
  78532. // get only scale! so the object could transform correctly.
  78533. var oldPosition = object.position.clone();
  78534. var oldRotation = object.rotation && object.rotation.clone();
  78535. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  78536. object.position.copyFromFloats(0, 0, 0);
  78537. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78538. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78539. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78540. var transform = object.computeWorldMatrix(true);
  78541. // convert rawVerts to object space
  78542. var temp = new Array();
  78543. var index;
  78544. for (index = 0; index < rawVerts.length; index += 3) {
  78545. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  78546. }
  78547. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  78548. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  78549. //now set back the transformation!
  78550. object.position.copyFrom(oldPosition);
  78551. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  78552. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  78553. break;
  78554. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  78555. var oldPosition2 = object.position.clone();
  78556. var oldRotation2 = object.rotation && object.rotation.clone();
  78557. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  78558. object.position.copyFromFloats(0, 0, 0);
  78559. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78560. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78561. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78562. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  78563. returnValue = this._createHeightmap(object);
  78564. object.position.copyFrom(oldPosition2);
  78565. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  78566. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  78567. object.computeWorldMatrix(true);
  78568. break;
  78569. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78570. returnValue = new this.BJSCANNON.Particle();
  78571. break;
  78572. }
  78573. return returnValue;
  78574. };
  78575. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  78576. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78577. var transform = object.computeWorldMatrix(true);
  78578. // convert rawVerts to object space
  78579. var temp = new Array();
  78580. var index;
  78581. for (index = 0; index < pos.length; index += 3) {
  78582. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  78583. }
  78584. pos = temp;
  78585. var matrix = new Array();
  78586. //For now pointDepth will not be used and will be automatically calculated.
  78587. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  78588. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  78589. var boundingInfo = object.getBoundingInfo();
  78590. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  78591. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  78592. var elementSize = dim * 2 / arraySize;
  78593. for (var i = 0; i < pos.length; i = i + 3) {
  78594. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  78595. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  78596. var y = -pos[i + 2] + minY;
  78597. if (!matrix[x]) {
  78598. matrix[x] = [];
  78599. }
  78600. if (!matrix[x][z]) {
  78601. matrix[x][z] = y;
  78602. }
  78603. matrix[x][z] = Math.max(y, matrix[x][z]);
  78604. }
  78605. for (var x = 0; x <= arraySize; ++x) {
  78606. if (!matrix[x]) {
  78607. var loc = 1;
  78608. while (!matrix[(x + loc) % arraySize]) {
  78609. loc++;
  78610. }
  78611. matrix[x] = matrix[(x + loc) % arraySize].slice();
  78612. //console.log("missing x", x);
  78613. }
  78614. for (var z = 0; z <= arraySize; ++z) {
  78615. if (!matrix[x][z]) {
  78616. var loc = 1;
  78617. var newValue;
  78618. while (newValue === undefined) {
  78619. newValue = matrix[x][(z + loc++) % arraySize];
  78620. }
  78621. matrix[x][z] = newValue;
  78622. }
  78623. }
  78624. }
  78625. var shape = new this.BJSCANNON.Heightfield(matrix, {
  78626. elementSize: elementSize
  78627. });
  78628. //For future reference, needed for body transformation
  78629. shape.minY = minY;
  78630. return shape;
  78631. };
  78632. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  78633. var object = impostor.object;
  78634. //make sure it is updated...
  78635. object.computeWorldMatrix && object.computeWorldMatrix(true);
  78636. // The delta between the mesh position and the mesh bounding box center
  78637. var bInfo = object.getBoundingInfo();
  78638. if (!bInfo)
  78639. return;
  78640. var center = impostor.getObjectCenter();
  78641. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  78642. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  78643. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  78644. this._tmpPosition.copyFrom(center);
  78645. var quaternion = object.rotationQuaternion;
  78646. if (!quaternion) {
  78647. return;
  78648. }
  78649. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  78650. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  78651. //-90 DEG in X, precalculated
  78652. quaternion = quaternion.multiply(this._minus90X);
  78653. //Invert! (Precalculated, 90 deg in X)
  78654. //No need to clone. this will never change.
  78655. impostor.setDeltaRotation(this._plus90X);
  78656. }
  78657. //If it is a heightfield, if should be centered.
  78658. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  78659. var mesh = object;
  78660. var boundingInfo = mesh.getBoundingInfo();
  78661. //calculate the correct body position:
  78662. var rotationQuaternion = mesh.rotationQuaternion;
  78663. mesh.rotationQuaternion = this._tmpUnityRotation;
  78664. mesh.computeWorldMatrix(true);
  78665. //get original center with no rotation
  78666. var c = center.clone();
  78667. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  78668. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  78669. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  78670. mesh.setPreTransformMatrix(p);
  78671. mesh.computeWorldMatrix(true);
  78672. //calculate the translation
  78673. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  78674. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  78675. //add it inverted to the delta
  78676. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  78677. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  78678. //rotation is back
  78679. mesh.rotationQuaternion = rotationQuaternion;
  78680. mesh.setPreTransformMatrix(oldPivot);
  78681. mesh.computeWorldMatrix(true);
  78682. }
  78683. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  78684. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  78685. //this._tmpPosition.copyFrom(object.position);
  78686. }
  78687. impostor.setDeltaPosition(this._tmpDeltaPosition);
  78688. //Now update the impostor object
  78689. impostor.physicsBody.position.copy(this._tmpPosition);
  78690. impostor.physicsBody.quaternion.copy(quaternion);
  78691. };
  78692. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  78693. impostor.object.position.copyFrom(impostor.physicsBody.position);
  78694. if (impostor.object.rotationQuaternion) {
  78695. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  78696. }
  78697. };
  78698. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  78699. impostor.physicsBody.position.copy(newPosition);
  78700. impostor.physicsBody.quaternion.copy(newRotation);
  78701. };
  78702. CannonJSPlugin.prototype.isSupported = function () {
  78703. return this.BJSCANNON !== undefined;
  78704. };
  78705. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  78706. impostor.physicsBody.velocity.copy(velocity);
  78707. };
  78708. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  78709. impostor.physicsBody.angularVelocity.copy(velocity);
  78710. };
  78711. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  78712. var v = impostor.physicsBody.velocity;
  78713. if (!v) {
  78714. return null;
  78715. }
  78716. return new BABYLON.Vector3(v.x, v.y, v.z);
  78717. };
  78718. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  78719. var v = impostor.physicsBody.angularVelocity;
  78720. if (!v) {
  78721. return null;
  78722. }
  78723. return new BABYLON.Vector3(v.x, v.y, v.z);
  78724. };
  78725. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78726. impostor.physicsBody.mass = mass;
  78727. impostor.physicsBody.updateMassProperties();
  78728. };
  78729. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  78730. return impostor.physicsBody.mass;
  78731. };
  78732. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  78733. return impostor.physicsBody.material.friction;
  78734. };
  78735. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78736. impostor.physicsBody.material.friction = friction;
  78737. };
  78738. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78739. return impostor.physicsBody.material.restitution;
  78740. };
  78741. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78742. impostor.physicsBody.material.restitution = restitution;
  78743. };
  78744. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  78745. impostor.physicsBody.sleep();
  78746. };
  78747. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  78748. impostor.physicsBody.wakeUp();
  78749. };
  78750. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78751. joint.physicsJoint.distance = maxDistance;
  78752. };
  78753. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78754. // if (!motorIndex) {
  78755. // joint.physicsJoint.enableMotor();
  78756. // }
  78757. // }
  78758. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78759. // if (!motorIndex) {
  78760. // joint.physicsJoint.disableMotor();
  78761. // }
  78762. // }
  78763. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78764. if (!motorIndex) {
  78765. joint.physicsJoint.enableMotor();
  78766. joint.physicsJoint.setMotorSpeed(speed);
  78767. if (maxForce) {
  78768. this.setLimit(joint, maxForce);
  78769. }
  78770. }
  78771. };
  78772. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  78773. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  78774. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  78775. };
  78776. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78777. var body = impostor.physicsBody;
  78778. mesh.position.x = body.position.x;
  78779. mesh.position.y = body.position.y;
  78780. mesh.position.z = body.position.z;
  78781. if (mesh.rotationQuaternion) {
  78782. mesh.rotationQuaternion.x = body.quaternion.x;
  78783. mesh.rotationQuaternion.y = body.quaternion.y;
  78784. mesh.rotationQuaternion.z = body.quaternion.z;
  78785. mesh.rotationQuaternion.w = body.quaternion.w;
  78786. }
  78787. };
  78788. CannonJSPlugin.prototype.getRadius = function (impostor) {
  78789. var shape = impostor.physicsBody.shapes[0];
  78790. return shape.boundingSphereRadius;
  78791. };
  78792. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78793. var shape = impostor.physicsBody.shapes[0];
  78794. result.x = shape.halfExtents.x * 2;
  78795. result.y = shape.halfExtents.y * 2;
  78796. result.z = shape.halfExtents.z * 2;
  78797. };
  78798. CannonJSPlugin.prototype.dispose = function () {
  78799. };
  78800. CannonJSPlugin.prototype._extendNamespace = function () {
  78801. //this will force cannon to execute at least one step when using interpolation
  78802. var step_tmp1 = new this.BJSCANNON.Vec3();
  78803. var Engine = this.BJSCANNON;
  78804. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  78805. maxSubSteps = maxSubSteps || 10;
  78806. timeSinceLastCalled = timeSinceLastCalled || 0;
  78807. if (timeSinceLastCalled === 0) {
  78808. this.internalStep(dt);
  78809. this.time += dt;
  78810. }
  78811. else {
  78812. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  78813. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  78814. var t0 = performance.now();
  78815. for (var i = 0; i !== internalSteps; i++) {
  78816. this.internalStep(dt);
  78817. if (performance.now() - t0 > dt * 1000) {
  78818. break;
  78819. }
  78820. }
  78821. this.time += timeSinceLastCalled;
  78822. var h = this.time % dt;
  78823. var h_div_dt = h / dt;
  78824. var interpvelo = step_tmp1;
  78825. var bodies = this.bodies;
  78826. for (var j = 0; j !== bodies.length; j++) {
  78827. var b = bodies[j];
  78828. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  78829. b.position.vsub(b.previousPosition, interpvelo);
  78830. interpvelo.scale(h_div_dt, interpvelo);
  78831. b.position.vadd(interpvelo, b.interpolatedPosition);
  78832. }
  78833. else {
  78834. b.interpolatedPosition.copy(b.position);
  78835. b.interpolatedQuaternion.copy(b.quaternion);
  78836. }
  78837. }
  78838. }
  78839. };
  78840. };
  78841. return CannonJSPlugin;
  78842. }());
  78843. BABYLON.CannonJSPlugin = CannonJSPlugin;
  78844. })(BABYLON || (BABYLON = {}));
  78845. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  78846. "use strict";
  78847. var BABYLON;
  78848. (function (BABYLON) {
  78849. var OimoJSPlugin = /** @class */ (function () {
  78850. function OimoJSPlugin(iterations) {
  78851. this.name = "OimoJSPlugin";
  78852. this._tmpImpostorsArray = [];
  78853. this._tmpPositionVector = BABYLON.Vector3.Zero();
  78854. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  78855. this.world = new this.BJSOIMO.World({
  78856. iterations: iterations
  78857. });
  78858. this.world.clear();
  78859. }
  78860. OimoJSPlugin.prototype.setGravity = function (gravity) {
  78861. this.world.gravity.copy(gravity);
  78862. };
  78863. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  78864. this.world.timeStep = timeStep;
  78865. };
  78866. OimoJSPlugin.prototype.getTimeStep = function () {
  78867. return this.world.timeStep;
  78868. };
  78869. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  78870. var _this = this;
  78871. impostors.forEach(function (impostor) {
  78872. impostor.beforeStep();
  78873. });
  78874. this.world.step();
  78875. impostors.forEach(function (impostor) {
  78876. impostor.afterStep();
  78877. //update the ordered impostors array
  78878. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  78879. });
  78880. //check for collisions
  78881. var contact = this.world.contacts;
  78882. while (contact !== null) {
  78883. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  78884. contact = contact.next;
  78885. continue;
  78886. }
  78887. //is this body colliding with any other? get the impostor
  78888. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  78889. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  78890. if (!mainImpostor || !collidingImpostor) {
  78891. contact = contact.next;
  78892. continue;
  78893. }
  78894. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  78895. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  78896. contact = contact.next;
  78897. }
  78898. };
  78899. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78900. var mass = impostor.physicsBody.mass;
  78901. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  78902. };
  78903. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78904. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  78905. this.applyImpulse(impostor, force, contactPoint);
  78906. };
  78907. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78908. var _this = this;
  78909. //parent-child relationship. Does this impostor has a parent impostor?
  78910. if (impostor.parent) {
  78911. if (impostor.physicsBody) {
  78912. this.removePhysicsBody(impostor);
  78913. //TODO is that needed?
  78914. impostor.forceUpdate();
  78915. }
  78916. return;
  78917. }
  78918. if (impostor.isBodyInitRequired()) {
  78919. var bodyConfig = {
  78920. name: impostor.uniqueId,
  78921. //Oimo must have mass, also for static objects.
  78922. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  78923. size: [],
  78924. type: [],
  78925. pos: [],
  78926. posShape: [],
  78927. rot: [],
  78928. rotShape: [],
  78929. move: impostor.getParam("mass") !== 0,
  78930. density: impostor.getParam("mass"),
  78931. friction: impostor.getParam("friction"),
  78932. restitution: impostor.getParam("restitution"),
  78933. //Supporting older versions of Oimo
  78934. world: this.world
  78935. };
  78936. var impostors = [impostor];
  78937. var addToArray = function (parent) {
  78938. if (!parent.getChildMeshes)
  78939. return;
  78940. parent.getChildMeshes().forEach(function (m) {
  78941. if (m.physicsImpostor) {
  78942. impostors.push(m.physicsImpostor);
  78943. //m.physicsImpostor._init();
  78944. }
  78945. });
  78946. };
  78947. addToArray(impostor.object);
  78948. var checkWithEpsilon_1 = function (value) {
  78949. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  78950. };
  78951. impostors.forEach(function (i) {
  78952. if (!i.object.rotationQuaternion) {
  78953. return;
  78954. }
  78955. //get the correct bounding box
  78956. var oldQuaternion = i.object.rotationQuaternion;
  78957. var rot = oldQuaternion.toEulerAngles();
  78958. var extendSize = i.getObjectExtendSize();
  78959. var radToDeg = 57.295779513082320876;
  78960. if (i === impostor) {
  78961. var center = impostor.getObjectCenter();
  78962. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  78963. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  78964. //Can also use Array.prototype.push.apply
  78965. bodyConfig.pos.push(center.x);
  78966. bodyConfig.pos.push(center.y);
  78967. bodyConfig.pos.push(center.z);
  78968. bodyConfig.posShape.push(0, 0, 0);
  78969. //tmp solution
  78970. bodyConfig.rot.push(rot.x * radToDeg);
  78971. bodyConfig.rot.push(rot.y * radToDeg);
  78972. bodyConfig.rot.push(rot.z * radToDeg);
  78973. bodyConfig.rotShape.push(0, 0, 0);
  78974. }
  78975. else {
  78976. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  78977. bodyConfig.posShape.push(localPosition.x);
  78978. bodyConfig.posShape.push(localPosition.y);
  78979. bodyConfig.posShape.push(localPosition.z);
  78980. bodyConfig.pos.push(0, 0, 0);
  78981. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  78982. bodyConfig.rot.push(0);
  78983. bodyConfig.rot.push(0);
  78984. bodyConfig.rot.push(0);
  78985. bodyConfig.rotShape.push(rot.x * radToDeg);
  78986. bodyConfig.rotShape.push(rot.y * radToDeg);
  78987. bodyConfig.rotShape.push(rot.z * radToDeg);
  78988. }
  78989. // register mesh
  78990. switch (i.type) {
  78991. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78992. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  78993. case BABYLON.PhysicsImpostor.SphereImpostor:
  78994. var radiusX = extendSize.x;
  78995. var radiusY = extendSize.y;
  78996. var radiusZ = extendSize.z;
  78997. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  78998. bodyConfig.type.push('sphere');
  78999. //due to the way oimo works with compounds, add 3 times
  79000. bodyConfig.size.push(size);
  79001. bodyConfig.size.push(size);
  79002. bodyConfig.size.push(size);
  79003. break;
  79004. case BABYLON.PhysicsImpostor.CylinderImpostor:
  79005. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  79006. var sizeY = checkWithEpsilon_1(extendSize.y);
  79007. bodyConfig.type.push('cylinder');
  79008. bodyConfig.size.push(sizeX);
  79009. bodyConfig.size.push(sizeY);
  79010. //due to the way oimo works with compounds, add one more value.
  79011. bodyConfig.size.push(sizeY);
  79012. break;
  79013. case BABYLON.PhysicsImpostor.PlaneImpostor:
  79014. case BABYLON.PhysicsImpostor.BoxImpostor:
  79015. default:
  79016. var sizeX = checkWithEpsilon_1(extendSize.x);
  79017. var sizeY = checkWithEpsilon_1(extendSize.y);
  79018. var sizeZ = checkWithEpsilon_1(extendSize.z);
  79019. bodyConfig.type.push('box');
  79020. //if (i === impostor) {
  79021. bodyConfig.size.push(sizeX);
  79022. bodyConfig.size.push(sizeY);
  79023. bodyConfig.size.push(sizeZ);
  79024. //} else {
  79025. // bodyConfig.size.push(0,0,0);
  79026. //}
  79027. break;
  79028. }
  79029. //actually not needed, but hey...
  79030. i.object.rotationQuaternion = oldQuaternion;
  79031. });
  79032. impostor.physicsBody = this.world.add(bodyConfig);
  79033. }
  79034. else {
  79035. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  79036. }
  79037. impostor.setDeltaPosition(this._tmpPositionVector);
  79038. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  79039. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  79040. };
  79041. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  79042. //impostor.physicsBody.dispose();
  79043. //Same as : (older oimo versions)
  79044. this.world.removeRigidBody(impostor.physicsBody);
  79045. };
  79046. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  79047. var mainBody = impostorJoint.mainImpostor.physicsBody;
  79048. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  79049. if (!mainBody || !connectedBody) {
  79050. return;
  79051. }
  79052. var jointData = impostorJoint.joint.jointData;
  79053. var options = jointData.nativeParams || {};
  79054. var type;
  79055. var nativeJointData = {
  79056. body1: mainBody,
  79057. body2: connectedBody,
  79058. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  79059. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  79060. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  79061. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  79062. min: options.min,
  79063. max: options.max,
  79064. collision: options.collision || jointData.collision,
  79065. spring: options.spring,
  79066. //supporting older version of Oimo
  79067. world: this.world
  79068. };
  79069. switch (impostorJoint.joint.type) {
  79070. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  79071. type = "jointBall";
  79072. break;
  79073. case BABYLON.PhysicsJoint.SpringJoint:
  79074. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  79075. var springData = jointData;
  79076. nativeJointData.min = springData.length || nativeJointData.min;
  79077. //Max should also be set, just make sure it is at least min
  79078. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  79079. case BABYLON.PhysicsJoint.DistanceJoint:
  79080. type = "jointDistance";
  79081. nativeJointData.max = jointData.maxDistance;
  79082. break;
  79083. case BABYLON.PhysicsJoint.PrismaticJoint:
  79084. type = "jointPrisme";
  79085. break;
  79086. case BABYLON.PhysicsJoint.SliderJoint:
  79087. type = "jointSlide";
  79088. break;
  79089. case BABYLON.PhysicsJoint.WheelJoint:
  79090. type = "jointWheel";
  79091. break;
  79092. case BABYLON.PhysicsJoint.HingeJoint:
  79093. default:
  79094. type = "jointHinge";
  79095. break;
  79096. }
  79097. nativeJointData.type = type;
  79098. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  79099. };
  79100. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  79101. //Bug in Oimo prevents us from disposing a joint in the playground
  79102. //joint.joint.physicsJoint.dispose();
  79103. //So we will bruteforce it!
  79104. try {
  79105. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  79106. }
  79107. catch (e) {
  79108. BABYLON.Tools.Warn(e);
  79109. }
  79110. };
  79111. OimoJSPlugin.prototype.isSupported = function () {
  79112. return this.BJSOIMO !== undefined;
  79113. };
  79114. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  79115. if (!impostor.physicsBody.sleeping) {
  79116. //TODO check that
  79117. /*if (impostor.physicsBody.shapes.next) {
  79118. var parentShape = this._getLastShape(impostor.physicsBody);
  79119. impostor.object.position.copyFrom(parentShape.position);
  79120. console.log(parentShape.position);
  79121. } else {*/
  79122. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  79123. //}
  79124. if (impostor.object.rotationQuaternion) {
  79125. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  79126. }
  79127. }
  79128. };
  79129. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  79130. var body = impostor.physicsBody;
  79131. body.position.copy(newPosition);
  79132. body.orientation.copy(newRotation);
  79133. body.syncShapes();
  79134. body.awake();
  79135. };
  79136. /*private _getLastShape(body: any): any {
  79137. var lastShape = body.shapes;
  79138. while (lastShape.next) {
  79139. lastShape = lastShape.next;
  79140. }
  79141. return lastShape;
  79142. }*/
  79143. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  79144. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  79145. };
  79146. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  79147. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  79148. };
  79149. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  79150. var v = impostor.physicsBody.linearVelocity;
  79151. if (!v) {
  79152. return null;
  79153. }
  79154. return new BABYLON.Vector3(v.x, v.y, v.z);
  79155. };
  79156. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  79157. var v = impostor.physicsBody.angularVelocity;
  79158. if (!v) {
  79159. return null;
  79160. }
  79161. return new BABYLON.Vector3(v.x, v.y, v.z);
  79162. };
  79163. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  79164. var staticBody = mass === 0;
  79165. //this will actually set the body's density and not its mass.
  79166. //But this is how oimo treats the mass variable.
  79167. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  79168. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  79169. };
  79170. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  79171. return impostor.physicsBody.shapes.density;
  79172. };
  79173. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  79174. return impostor.physicsBody.shapes.friction;
  79175. };
  79176. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  79177. impostor.physicsBody.shapes.friction = friction;
  79178. };
  79179. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  79180. return impostor.physicsBody.shapes.restitution;
  79181. };
  79182. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  79183. impostor.physicsBody.shapes.restitution = restitution;
  79184. };
  79185. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  79186. impostor.physicsBody.sleep();
  79187. };
  79188. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  79189. impostor.physicsBody.awake();
  79190. };
  79191. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  79192. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  79193. if (minDistance !== void 0) {
  79194. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  79195. }
  79196. };
  79197. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  79198. //TODO separate rotational and transational motors.
  79199. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79200. if (motor) {
  79201. motor.setMotor(speed, maxForce);
  79202. }
  79203. };
  79204. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  79205. //TODO separate rotational and transational motors.
  79206. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79207. if (motor) {
  79208. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  79209. }
  79210. };
  79211. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  79212. var body = impostor.physicsBody;
  79213. mesh.position.x = body.position.x;
  79214. mesh.position.y = body.position.y;
  79215. mesh.position.z = body.position.z;
  79216. if (mesh.rotationQuaternion) {
  79217. mesh.rotationQuaternion.x = body.orientation.x;
  79218. mesh.rotationQuaternion.y = body.orientation.y;
  79219. mesh.rotationQuaternion.z = body.orientation.z;
  79220. mesh.rotationQuaternion.w = body.orientation.s;
  79221. }
  79222. };
  79223. OimoJSPlugin.prototype.getRadius = function (impostor) {
  79224. return impostor.physicsBody.shapes.radius;
  79225. };
  79226. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  79227. var shape = impostor.physicsBody.shapes;
  79228. result.x = shape.halfWidth * 2;
  79229. result.y = shape.halfHeight * 2;
  79230. result.z = shape.halfDepth * 2;
  79231. };
  79232. OimoJSPlugin.prototype.dispose = function () {
  79233. this.world.clear();
  79234. };
  79235. return OimoJSPlugin;
  79236. }());
  79237. BABYLON.OimoJSPlugin = OimoJSPlugin;
  79238. })(BABYLON || (BABYLON = {}));
  79239. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  79240. "use strict";
  79241. var BABYLON;
  79242. (function (BABYLON) {
  79243. /*
  79244. * Based on jsTGALoader - Javascript loader for TGA file
  79245. * By Vincent Thibault
  79246. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  79247. */
  79248. var TGATools = /** @class */ (function () {
  79249. function TGATools() {
  79250. }
  79251. TGATools.GetTGAHeader = function (data) {
  79252. var offset = 0;
  79253. var header = {
  79254. id_length: data[offset++],
  79255. colormap_type: data[offset++],
  79256. image_type: data[offset++],
  79257. colormap_index: data[offset++] | data[offset++] << 8,
  79258. colormap_length: data[offset++] | data[offset++] << 8,
  79259. colormap_size: data[offset++],
  79260. origin: [
  79261. data[offset++] | data[offset++] << 8,
  79262. data[offset++] | data[offset++] << 8
  79263. ],
  79264. width: data[offset++] | data[offset++] << 8,
  79265. height: data[offset++] | data[offset++] << 8,
  79266. pixel_size: data[offset++],
  79267. flags: data[offset++]
  79268. };
  79269. return header;
  79270. };
  79271. TGATools.UploadContent = function (gl, data) {
  79272. // Not enough data to contain header ?
  79273. if (data.length < 19) {
  79274. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  79275. return;
  79276. }
  79277. // Read Header
  79278. var offset = 18;
  79279. var header = TGATools.GetTGAHeader(data);
  79280. // Assume it's a valid Targa file.
  79281. if (header.id_length + offset > data.length) {
  79282. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  79283. return;
  79284. }
  79285. // Skip not needed data
  79286. offset += header.id_length;
  79287. var use_rle = false;
  79288. var use_pal = false;
  79289. var use_grey = false;
  79290. // Get some informations.
  79291. switch (header.image_type) {
  79292. case TGATools._TYPE_RLE_INDEXED:
  79293. use_rle = true;
  79294. case TGATools._TYPE_INDEXED:
  79295. use_pal = true;
  79296. break;
  79297. case TGATools._TYPE_RLE_RGB:
  79298. use_rle = true;
  79299. case TGATools._TYPE_RGB:
  79300. // use_rgb = true;
  79301. break;
  79302. case TGATools._TYPE_RLE_GREY:
  79303. use_rle = true;
  79304. case TGATools._TYPE_GREY:
  79305. use_grey = true;
  79306. break;
  79307. }
  79308. var pixel_data;
  79309. // var numAlphaBits = header.flags & 0xf;
  79310. var pixel_size = header.pixel_size >> 3;
  79311. var pixel_total = header.width * header.height * pixel_size;
  79312. // Read palettes
  79313. var palettes;
  79314. if (use_pal) {
  79315. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  79316. }
  79317. // Read LRE
  79318. if (use_rle) {
  79319. pixel_data = new Uint8Array(pixel_total);
  79320. var c, count, i;
  79321. var localOffset = 0;
  79322. var pixels = new Uint8Array(pixel_size);
  79323. while (offset < pixel_total && localOffset < pixel_total) {
  79324. c = data[offset++];
  79325. count = (c & 0x7f) + 1;
  79326. // RLE pixels
  79327. if (c & 0x80) {
  79328. // Bind pixel tmp array
  79329. for (i = 0; i < pixel_size; ++i) {
  79330. pixels[i] = data[offset++];
  79331. }
  79332. // Copy pixel array
  79333. for (i = 0; i < count; ++i) {
  79334. pixel_data.set(pixels, localOffset + i * pixel_size);
  79335. }
  79336. localOffset += pixel_size * count;
  79337. }
  79338. else {
  79339. count *= pixel_size;
  79340. for (i = 0; i < count; ++i) {
  79341. pixel_data[localOffset + i] = data[offset++];
  79342. }
  79343. localOffset += count;
  79344. }
  79345. }
  79346. }
  79347. else {
  79348. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  79349. }
  79350. // Load to texture
  79351. var x_start, y_start, x_step, y_step, y_end, x_end;
  79352. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  79353. default:
  79354. case TGATools._ORIGIN_UL:
  79355. x_start = 0;
  79356. x_step = 1;
  79357. x_end = header.width;
  79358. y_start = 0;
  79359. y_step = 1;
  79360. y_end = header.height;
  79361. break;
  79362. case TGATools._ORIGIN_BL:
  79363. x_start = 0;
  79364. x_step = 1;
  79365. x_end = header.width;
  79366. y_start = header.height - 1;
  79367. y_step = -1;
  79368. y_end = -1;
  79369. break;
  79370. case TGATools._ORIGIN_UR:
  79371. x_start = header.width - 1;
  79372. x_step = -1;
  79373. x_end = -1;
  79374. y_start = 0;
  79375. y_step = 1;
  79376. y_end = header.height;
  79377. break;
  79378. case TGATools._ORIGIN_BR:
  79379. x_start = header.width - 1;
  79380. x_step = -1;
  79381. x_end = -1;
  79382. y_start = header.height - 1;
  79383. y_step = -1;
  79384. y_end = -1;
  79385. break;
  79386. }
  79387. // Load the specify method
  79388. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  79389. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  79390. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  79391. };
  79392. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79393. var image = pixel_data, colormap = palettes;
  79394. var width = header.width, height = header.height;
  79395. var color, i = 0, x, y;
  79396. var imageData = new Uint8Array(width * height * 4);
  79397. for (y = y_start; y !== y_end; y += y_step) {
  79398. for (x = x_start; x !== x_end; x += x_step, i++) {
  79399. color = image[i];
  79400. imageData[(x + width * y) * 4 + 3] = 255;
  79401. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  79402. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  79403. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  79404. }
  79405. }
  79406. return imageData;
  79407. };
  79408. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79409. var image = pixel_data;
  79410. var width = header.width, height = header.height;
  79411. var color, i = 0, x, y;
  79412. var imageData = new Uint8Array(width * height * 4);
  79413. for (y = y_start; y !== y_end; y += y_step) {
  79414. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79415. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  79416. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  79417. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  79418. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  79419. imageData[(x + width * y) * 4 + 0] = r;
  79420. imageData[(x + width * y) * 4 + 1] = g;
  79421. imageData[(x + width * y) * 4 + 2] = b;
  79422. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  79423. }
  79424. }
  79425. return imageData;
  79426. };
  79427. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79428. var image = pixel_data;
  79429. var width = header.width, height = header.height;
  79430. var i = 0, x, y;
  79431. var imageData = new Uint8Array(width * height * 4);
  79432. for (y = y_start; y !== y_end; y += y_step) {
  79433. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  79434. imageData[(x + width * y) * 4 + 3] = 255;
  79435. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79436. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79437. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79438. }
  79439. }
  79440. return imageData;
  79441. };
  79442. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79443. var image = pixel_data;
  79444. var width = header.width, height = header.height;
  79445. var i = 0, x, y;
  79446. var imageData = new Uint8Array(width * height * 4);
  79447. for (y = y_start; y !== y_end; y += y_step) {
  79448. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  79449. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79450. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79451. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79452. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  79453. }
  79454. }
  79455. return imageData;
  79456. };
  79457. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79458. var image = pixel_data;
  79459. var width = header.width, height = header.height;
  79460. var color, i = 0, x, y;
  79461. var imageData = new Uint8Array(width * height * 4);
  79462. for (y = y_start; y !== y_end; y += y_step) {
  79463. for (x = x_start; x !== x_end; x += x_step, i++) {
  79464. color = image[i];
  79465. imageData[(x + width * y) * 4 + 0] = color;
  79466. imageData[(x + width * y) * 4 + 1] = color;
  79467. imageData[(x + width * y) * 4 + 2] = color;
  79468. imageData[(x + width * y) * 4 + 3] = 255;
  79469. }
  79470. }
  79471. return imageData;
  79472. };
  79473. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79474. var image = pixel_data;
  79475. var width = header.width, height = header.height;
  79476. var i = 0, x, y;
  79477. var imageData = new Uint8Array(width * height * 4);
  79478. for (y = y_start; y !== y_end; y += y_step) {
  79479. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79480. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  79481. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  79482. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79483. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  79484. }
  79485. }
  79486. return imageData;
  79487. };
  79488. //private static _TYPE_NO_DATA = 0;
  79489. TGATools._TYPE_INDEXED = 1;
  79490. TGATools._TYPE_RGB = 2;
  79491. TGATools._TYPE_GREY = 3;
  79492. TGATools._TYPE_RLE_INDEXED = 9;
  79493. TGATools._TYPE_RLE_RGB = 10;
  79494. TGATools._TYPE_RLE_GREY = 11;
  79495. TGATools._ORIGIN_MASK = 0x30;
  79496. TGATools._ORIGIN_SHIFT = 0x04;
  79497. TGATools._ORIGIN_BL = 0x00;
  79498. TGATools._ORIGIN_BR = 0x01;
  79499. TGATools._ORIGIN_UL = 0x02;
  79500. TGATools._ORIGIN_UR = 0x03;
  79501. return TGATools;
  79502. }());
  79503. BABYLON.TGATools = TGATools;
  79504. })(BABYLON || (BABYLON = {}));
  79505. //# sourceMappingURL=babylon.tga.js.map
  79506. "use strict";
  79507. var BABYLON;
  79508. (function (BABYLON) {
  79509. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  79510. // All values and structures referenced from:
  79511. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  79512. var DDS_MAGIC = 0x20534444;
  79513. var
  79514. //DDSD_CAPS = 0x1,
  79515. //DDSD_HEIGHT = 0x2,
  79516. //DDSD_WIDTH = 0x4,
  79517. //DDSD_PITCH = 0x8,
  79518. //DDSD_PIXELFORMAT = 0x1000,
  79519. DDSD_MIPMAPCOUNT = 0x20000;
  79520. //DDSD_LINEARSIZE = 0x80000,
  79521. //DDSD_DEPTH = 0x800000;
  79522. // var DDSCAPS_COMPLEX = 0x8,
  79523. // DDSCAPS_MIPMAP = 0x400000,
  79524. // DDSCAPS_TEXTURE = 0x1000;
  79525. var DDSCAPS2_CUBEMAP = 0x200;
  79526. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  79527. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  79528. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  79529. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  79530. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  79531. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  79532. // DDSCAPS2_VOLUME = 0x200000;
  79533. var
  79534. //DDPF_ALPHAPIXELS = 0x1,
  79535. //DDPF_ALPHA = 0x2,
  79536. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  79537. //DDPF_YUV = 0x200,
  79538. DDPF_LUMINANCE = 0x20000;
  79539. function FourCCToInt32(value) {
  79540. return value.charCodeAt(0) +
  79541. (value.charCodeAt(1) << 8) +
  79542. (value.charCodeAt(2) << 16) +
  79543. (value.charCodeAt(3) << 24);
  79544. }
  79545. function Int32ToFourCC(value) {
  79546. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  79547. }
  79548. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  79549. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  79550. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  79551. var FOURCC_DX10 = FourCCToInt32("DX10");
  79552. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  79553. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  79554. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  79555. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  79556. var headerLengthInt = 31; // The header length in 32 bit ints
  79557. // Offsets into the header array
  79558. var off_magic = 0;
  79559. var off_size = 1;
  79560. var off_flags = 2;
  79561. var off_height = 3;
  79562. var off_width = 4;
  79563. var off_mipmapCount = 7;
  79564. var off_pfFlags = 20;
  79565. var off_pfFourCC = 21;
  79566. var off_RGBbpp = 22;
  79567. var off_RMask = 23;
  79568. var off_GMask = 24;
  79569. var off_BMask = 25;
  79570. var off_AMask = 26;
  79571. // var off_caps1 = 27;
  79572. var off_caps2 = 28;
  79573. // var off_caps3 = 29;
  79574. // var off_caps4 = 30;
  79575. var off_dxgiFormat = 32;
  79576. ;
  79577. var DDSTools = /** @class */ (function () {
  79578. function DDSTools() {
  79579. }
  79580. DDSTools.GetDDSInfo = function (arrayBuffer) {
  79581. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79582. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  79583. var mipmapCount = 1;
  79584. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  79585. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79586. }
  79587. var fourCC = header[off_pfFourCC];
  79588. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  79589. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79590. switch (fourCC) {
  79591. case FOURCC_D3DFMT_R16G16B16A16F:
  79592. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79593. break;
  79594. case FOURCC_D3DFMT_R32G32B32A32F:
  79595. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79596. break;
  79597. case FOURCC_DX10:
  79598. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  79599. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79600. break;
  79601. }
  79602. }
  79603. return {
  79604. width: header[off_width],
  79605. height: header[off_height],
  79606. mipmapCount: mipmapCount,
  79607. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  79608. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  79609. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  79610. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  79611. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  79612. dxgiFormat: dxgiFormat,
  79613. textureType: textureType
  79614. };
  79615. };
  79616. DDSTools._ToHalfFloat = function (value) {
  79617. if (!DDSTools._FloatView) {
  79618. DDSTools._FloatView = new Float32Array(1);
  79619. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  79620. }
  79621. DDSTools._FloatView[0] = value;
  79622. var x = DDSTools._Int32View[0];
  79623. var bits = (x >> 16) & 0x8000; /* Get the sign */
  79624. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  79625. var e = (x >> 23) & 0xff; /* Using int is faster here */
  79626. /* If zero, or denormal, or exponent underflows too much for a denormal
  79627. * half, return signed zero. */
  79628. if (e < 103) {
  79629. return bits;
  79630. }
  79631. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  79632. if (e > 142) {
  79633. bits |= 0x7c00;
  79634. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  79635. * not Inf, so make sure we set one mantissa bit too. */
  79636. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  79637. return bits;
  79638. }
  79639. /* If exponent underflows but not too much, return a denormal */
  79640. if (e < 113) {
  79641. m |= 0x0800;
  79642. /* Extra rounding may overflow and set mantissa to 0 and exponent
  79643. * to 1, which is OK. */
  79644. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  79645. return bits;
  79646. }
  79647. bits |= ((e - 112) << 10) | (m >> 1);
  79648. bits += m & 1;
  79649. return bits;
  79650. };
  79651. DDSTools._FromHalfFloat = function (value) {
  79652. var s = (value & 0x8000) >> 15;
  79653. var e = (value & 0x7C00) >> 10;
  79654. var f = value & 0x03FF;
  79655. if (e === 0) {
  79656. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  79657. }
  79658. else if (e == 0x1F) {
  79659. return f ? NaN : ((s ? -1 : 1) * Infinity);
  79660. }
  79661. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  79662. };
  79663. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79664. var destArray = new Float32Array(dataLength);
  79665. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79666. var index = 0;
  79667. for (var y = 0; y < height; y++) {
  79668. for (var x = 0; x < width; x++) {
  79669. var srcPos = (x + y * width) * 4;
  79670. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  79671. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  79672. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  79673. if (DDSTools.StoreLODInAlphaChannel) {
  79674. destArray[index + 3] = lod;
  79675. }
  79676. else {
  79677. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  79678. }
  79679. index += 4;
  79680. }
  79681. }
  79682. return destArray;
  79683. };
  79684. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79685. if (DDSTools.StoreLODInAlphaChannel) {
  79686. var destArray = new Uint16Array(dataLength);
  79687. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79688. var index = 0;
  79689. for (var y = 0; y < height; y++) {
  79690. for (var x = 0; x < width; x++) {
  79691. var srcPos = (x + y * width) * 4;
  79692. destArray[index] = srcData[srcPos];
  79693. destArray[index + 1] = srcData[srcPos + 1];
  79694. destArray[index + 2] = srcData[srcPos + 2];
  79695. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  79696. index += 4;
  79697. }
  79698. }
  79699. return destArray;
  79700. }
  79701. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  79702. };
  79703. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79704. if (DDSTools.StoreLODInAlphaChannel) {
  79705. var destArray = new Float32Array(dataLength);
  79706. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79707. var index = 0;
  79708. for (var y = 0; y < height; y++) {
  79709. for (var x = 0; x < width; x++) {
  79710. var srcPos = (x + y * width) * 4;
  79711. destArray[index] = srcData[srcPos];
  79712. destArray[index + 1] = srcData[srcPos + 1];
  79713. destArray[index + 2] = srcData[srcPos + 2];
  79714. destArray[index + 3] = lod;
  79715. index += 4;
  79716. }
  79717. }
  79718. return destArray;
  79719. }
  79720. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  79721. };
  79722. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79723. var destArray = new Uint8Array(dataLength);
  79724. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79725. var index = 0;
  79726. for (var y = 0; y < height; y++) {
  79727. for (var x = 0; x < width; x++) {
  79728. var srcPos = (x + y * width) * 4;
  79729. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  79730. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  79731. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  79732. if (DDSTools.StoreLODInAlphaChannel) {
  79733. destArray[index + 3] = lod;
  79734. }
  79735. else {
  79736. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  79737. }
  79738. index += 4;
  79739. }
  79740. }
  79741. return destArray;
  79742. };
  79743. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79744. var destArray = new Uint8Array(dataLength);
  79745. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79746. var index = 0;
  79747. for (var y = 0; y < height; y++) {
  79748. for (var x = 0; x < width; x++) {
  79749. var srcPos = (x + y * width) * 4;
  79750. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  79751. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  79752. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  79753. if (DDSTools.StoreLODInAlphaChannel) {
  79754. destArray[index + 3] = lod;
  79755. }
  79756. else {
  79757. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  79758. }
  79759. index += 4;
  79760. }
  79761. }
  79762. return destArray;
  79763. };
  79764. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  79765. var byteArray = new Uint8Array(dataLength);
  79766. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79767. var index = 0;
  79768. for (var y = 0; y < height; y++) {
  79769. for (var x = 0; x < width; x++) {
  79770. var srcPos = (x + y * width) * 4;
  79771. byteArray[index] = srcData[srcPos + rOffset];
  79772. byteArray[index + 1] = srcData[srcPos + gOffset];
  79773. byteArray[index + 2] = srcData[srcPos + bOffset];
  79774. byteArray[index + 3] = srcData[srcPos + aOffset];
  79775. index += 4;
  79776. }
  79777. }
  79778. return byteArray;
  79779. };
  79780. DDSTools._ExtractLongWordOrder = function (value) {
  79781. if (value === 0 || value === 255 || value === -16777216) {
  79782. return 0;
  79783. }
  79784. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  79785. };
  79786. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  79787. var byteArray = new Uint8Array(dataLength);
  79788. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79789. var index = 0;
  79790. for (var y = 0; y < height; y++) {
  79791. for (var x = 0; x < width; x++) {
  79792. var srcPos = (x + y * width) * 3;
  79793. byteArray[index] = srcData[srcPos + rOffset];
  79794. byteArray[index + 1] = srcData[srcPos + gOffset];
  79795. byteArray[index + 2] = srcData[srcPos + bOffset];
  79796. index += 3;
  79797. }
  79798. }
  79799. return byteArray;
  79800. };
  79801. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  79802. var byteArray = new Uint8Array(dataLength);
  79803. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79804. var index = 0;
  79805. for (var y = 0; y < height; y++) {
  79806. for (var x = 0; x < width; x++) {
  79807. var srcPos = (x + y * width);
  79808. byteArray[index] = srcData[srcPos];
  79809. index++;
  79810. }
  79811. }
  79812. return byteArray;
  79813. };
  79814. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  79815. if (lodIndex === void 0) { lodIndex = -1; }
  79816. var ext = engine.getCaps().s3tc;
  79817. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79818. var fourCC, width, height, dataLength = 0, dataOffset;
  79819. var byteArray, mipmapCount, mip;
  79820. var internalFormat = 0;
  79821. var format = 0;
  79822. var blockBytes = 1;
  79823. if (header[off_magic] !== DDS_MAGIC) {
  79824. BABYLON.Tools.Error("Invalid magic number in DDS header");
  79825. return;
  79826. }
  79827. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  79828. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  79829. return;
  79830. }
  79831. if (info.isCompressed && !ext) {
  79832. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  79833. return;
  79834. }
  79835. var bpp = header[off_RGBbpp];
  79836. dataOffset = header[off_size] + 4;
  79837. var computeFormats = false;
  79838. if (info.isFourCC) {
  79839. fourCC = header[off_pfFourCC];
  79840. switch (fourCC) {
  79841. case FOURCC_DXT1:
  79842. blockBytes = 8;
  79843. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  79844. break;
  79845. case FOURCC_DXT3:
  79846. blockBytes = 16;
  79847. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  79848. break;
  79849. case FOURCC_DXT5:
  79850. blockBytes = 16;
  79851. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  79852. break;
  79853. case FOURCC_D3DFMT_R16G16B16A16F:
  79854. computeFormats = true;
  79855. break;
  79856. case FOURCC_D3DFMT_R32G32B32A32F:
  79857. computeFormats = true;
  79858. break;
  79859. case FOURCC_DX10:
  79860. // There is an additionnal header so dataOffset need to be changed
  79861. dataOffset += 5 * 4; // 5 uints
  79862. var supported = false;
  79863. switch (info.dxgiFormat) {
  79864. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  79865. computeFormats = true;
  79866. supported = true;
  79867. break;
  79868. case DXGI_FORMAT_B8G8R8X8_UNORM:
  79869. info.isRGB = true;
  79870. info.isFourCC = false;
  79871. bpp = 32;
  79872. supported = true;
  79873. break;
  79874. }
  79875. if (supported) {
  79876. break;
  79877. }
  79878. default:
  79879. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  79880. return;
  79881. }
  79882. }
  79883. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  79884. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  79885. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  79886. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  79887. if (computeFormats) {
  79888. format = engine._getWebGLTextureType(info.textureType);
  79889. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79890. }
  79891. mipmapCount = 1;
  79892. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  79893. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79894. }
  79895. for (var face = 0; face < faces; face++) {
  79896. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  79897. width = header[off_width];
  79898. height = header[off_height];
  79899. for (mip = 0; mip < mipmapCount; ++mip) {
  79900. if (lodIndex === -1 || lodIndex === mip) {
  79901. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  79902. var i = (lodIndex === -1) ? mip : 0;
  79903. if (!info.isCompressed && info.isFourCC) {
  79904. dataLength = width * height * 4;
  79905. var floatArray = null;
  79906. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  79907. if (bpp === 128) {
  79908. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79909. }
  79910. else if (bpp === 64) {
  79911. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79912. }
  79913. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79914. format = engine._getWebGLTextureType(info.textureType);
  79915. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79916. }
  79917. else {
  79918. if (bpp === 128) {
  79919. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79920. }
  79921. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  79922. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79923. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79924. format = engine._getWebGLTextureType(info.textureType);
  79925. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79926. }
  79927. else {
  79928. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79929. }
  79930. }
  79931. if (floatArray) {
  79932. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  79933. }
  79934. }
  79935. else if (info.isRGB) {
  79936. if (bpp === 24) {
  79937. dataLength = width * height * 3;
  79938. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  79939. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  79940. }
  79941. else {
  79942. dataLength = width * height * 4;
  79943. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  79944. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  79945. }
  79946. }
  79947. else if (info.isLuminance) {
  79948. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  79949. var unpaddedRowSize = width;
  79950. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  79951. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  79952. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  79953. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  79954. }
  79955. else {
  79956. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  79957. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  79958. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  79959. }
  79960. }
  79961. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  79962. width *= 0.5;
  79963. height *= 0.5;
  79964. width = Math.max(1.0, width);
  79965. height = Math.max(1.0, height);
  79966. }
  79967. if (currentFace !== undefined) {
  79968. // Loading a single face
  79969. break;
  79970. }
  79971. }
  79972. };
  79973. DDSTools.StoreLODInAlphaChannel = false;
  79974. return DDSTools;
  79975. }());
  79976. BABYLON.DDSTools = DDSTools;
  79977. })(BABYLON || (BABYLON = {}));
  79978. //# sourceMappingURL=babylon.dds.js.map
  79979. "use strict";
  79980. var BABYLON;
  79981. (function (BABYLON) {
  79982. /**
  79983. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  79984. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  79985. */
  79986. var KhronosTextureContainer = /** @class */ (function () {
  79987. /**
  79988. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  79989. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  79990. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  79991. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  79992. */
  79993. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  79994. this.arrayBuffer = arrayBuffer;
  79995. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  79996. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  79997. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  79998. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  79999. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  80000. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  80001. BABYLON.Tools.Error("texture missing KTX identifier");
  80002. return;
  80003. }
  80004. // load the reset of the header in native 32 bit int
  80005. var header = new Int32Array(this.arrayBuffer, 12, 13);
  80006. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  80007. var oppositeEndianess = header[0] === 0x01020304;
  80008. // read all the header elements in order they exist in the file, without modification (sans endainness)
  80009. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  80010. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  80011. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  80012. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  80013. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  80014. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  80015. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  80016. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  80017. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  80018. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  80019. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  80020. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  80021. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  80022. if (this.glType !== 0) {
  80023. BABYLON.Tools.Error("only compressed formats currently supported");
  80024. return;
  80025. }
  80026. else {
  80027. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  80028. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  80029. }
  80030. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  80031. BABYLON.Tools.Error("only 2D textures currently supported");
  80032. return;
  80033. }
  80034. if (this.numberOfArrayElements !== 0) {
  80035. BABYLON.Tools.Error("texture arrays not currently supported");
  80036. return;
  80037. }
  80038. if (this.numberOfFaces !== facesExpected) {
  80039. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  80040. return;
  80041. }
  80042. // we now have a completely validated file, so could use existence of loadType as success
  80043. // would need to make this more elaborate & adjust checks above to support more than one load type
  80044. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  80045. }
  80046. // not as fast hardware based, but will probably never need to use
  80047. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  80048. return ((val & 0xFF) << 24)
  80049. | ((val & 0xFF00) << 8)
  80050. | ((val >> 8) & 0xFF00)
  80051. | ((val >> 24) & 0xFF);
  80052. };
  80053. /**
  80054. * It is assumed that the texture has already been created & is currently bound
  80055. */
  80056. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  80057. switch (this.loadType) {
  80058. case KhronosTextureContainer.COMPRESSED_2D:
  80059. this._upload2DCompressedLevels(gl, loadMipmaps);
  80060. break;
  80061. case KhronosTextureContainer.TEX_2D:
  80062. case KhronosTextureContainer.COMPRESSED_3D:
  80063. case KhronosTextureContainer.TEX_3D:
  80064. }
  80065. };
  80066. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  80067. // initialize width & height for level 1
  80068. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  80069. var width = this.pixelWidth;
  80070. var height = this.pixelHeight;
  80071. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  80072. for (var level = 0; level < mipmapCount; level++) {
  80073. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  80074. for (var face = 0; face < this.numberOfFaces; face++) {
  80075. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  80076. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  80077. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  80078. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  80079. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  80080. }
  80081. width = Math.max(1.0, width * 0.5);
  80082. height = Math.max(1.0, height * 0.5);
  80083. }
  80084. };
  80085. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  80086. // load types
  80087. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  80088. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  80089. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  80090. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  80091. return KhronosTextureContainer;
  80092. }());
  80093. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  80094. })(BABYLON || (BABYLON = {}));
  80095. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  80096. "use strict";
  80097. var BABYLON;
  80098. (function (BABYLON) {
  80099. var Debug = /** @class */ (function () {
  80100. function Debug() {
  80101. }
  80102. Debug.AxesViewer = /** @class */ (function () {
  80103. function AxesViewer(scene, scaleLines) {
  80104. if (scaleLines === void 0) { scaleLines = 1; }
  80105. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80106. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80107. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80108. this.scaleLines = 1;
  80109. this.scaleLines = scaleLines;
  80110. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  80111. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  80112. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  80113. this._xmesh.renderingGroupId = 2;
  80114. this._ymesh.renderingGroupId = 2;
  80115. this._zmesh.renderingGroupId = 2;
  80116. this._xmesh.material.checkReadyOnlyOnce = true;
  80117. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  80118. this._ymesh.material.checkReadyOnlyOnce = true;
  80119. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  80120. this._zmesh.material.checkReadyOnlyOnce = true;
  80121. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  80122. this.scene = scene;
  80123. }
  80124. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  80125. var scaleLines = this.scaleLines;
  80126. if (this._xmesh) {
  80127. this._xmesh.position.copyFrom(position);
  80128. }
  80129. if (this._ymesh) {
  80130. this._ymesh.position.copyFrom(position);
  80131. }
  80132. if (this._zmesh) {
  80133. this._zmesh.position.copyFrom(position);
  80134. }
  80135. var point2 = this._xline[1];
  80136. point2.x = xaxis.x * scaleLines;
  80137. point2.y = xaxis.y * scaleLines;
  80138. point2.z = xaxis.z * scaleLines;
  80139. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  80140. point2 = this._yline[1];
  80141. point2.x = yaxis.x * scaleLines;
  80142. point2.y = yaxis.y * scaleLines;
  80143. point2.z = yaxis.z * scaleLines;
  80144. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  80145. point2 = this._zline[1];
  80146. point2.x = zaxis.x * scaleLines;
  80147. point2.y = zaxis.y * scaleLines;
  80148. point2.z = zaxis.z * scaleLines;
  80149. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  80150. };
  80151. AxesViewer.prototype.dispose = function () {
  80152. if (this._xmesh) {
  80153. this._xmesh.dispose();
  80154. }
  80155. if (this._ymesh) {
  80156. this._ymesh.dispose();
  80157. }
  80158. if (this._zmesh) {
  80159. this._zmesh.dispose();
  80160. }
  80161. this._xmesh = null;
  80162. this._ymesh = null;
  80163. this._zmesh = null;
  80164. this.scene = null;
  80165. };
  80166. return AxesViewer;
  80167. }());
  80168. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  80169. __extends(BoneAxesViewer, _super);
  80170. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  80171. if (scaleLines === void 0) { scaleLines = 1; }
  80172. var _this = _super.call(this, scene, scaleLines) || this;
  80173. _this.pos = BABYLON.Vector3.Zero();
  80174. _this.xaxis = BABYLON.Vector3.Zero();
  80175. _this.yaxis = BABYLON.Vector3.Zero();
  80176. _this.zaxis = BABYLON.Vector3.Zero();
  80177. _this.mesh = mesh;
  80178. _this.bone = bone;
  80179. return _this;
  80180. }
  80181. BoneAxesViewer.prototype.update = function () {
  80182. if (!this.mesh || !this.bone) {
  80183. return;
  80184. }
  80185. var bone = this.bone;
  80186. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  80187. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  80188. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  80189. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  80190. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  80191. };
  80192. BoneAxesViewer.prototype.dispose = function () {
  80193. if (this.mesh) {
  80194. this.mesh = null;
  80195. this.bone = null;
  80196. _super.prototype.dispose.call(this);
  80197. }
  80198. };
  80199. return BoneAxesViewer;
  80200. }(Debug.AxesViewer));
  80201. Debug.PhysicsViewer = /** @class */ (function () {
  80202. function PhysicsViewer(scene) {
  80203. this._impostors = [];
  80204. this._meshes = [];
  80205. this._numMeshes = 0;
  80206. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80207. var physicEngine = this._scene.getPhysicsEngine();
  80208. if (physicEngine) {
  80209. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  80210. }
  80211. }
  80212. PhysicsViewer.prototype._updateDebugMeshes = function () {
  80213. var plugin = this._physicsEnginePlugin;
  80214. for (var i = 0; i < this._numMeshes; i++) {
  80215. var impostor = this._impostors[i];
  80216. if (!impostor) {
  80217. continue;
  80218. }
  80219. if (impostor.isDisposed) {
  80220. this.hideImpostor(this._impostors[i--]);
  80221. }
  80222. else {
  80223. var mesh = this._meshes[i];
  80224. if (mesh && plugin) {
  80225. plugin.syncMeshWithImpostor(mesh, impostor);
  80226. }
  80227. }
  80228. }
  80229. };
  80230. PhysicsViewer.prototype.showImpostor = function (impostor) {
  80231. if (!this._scene) {
  80232. return;
  80233. }
  80234. for (var i = 0; i < this._numMeshes; i++) {
  80235. if (this._impostors[i] == impostor) {
  80236. return;
  80237. }
  80238. }
  80239. var debugMesh = this._getDebugMesh(impostor, this._scene);
  80240. if (debugMesh) {
  80241. this._impostors[this._numMeshes] = impostor;
  80242. this._meshes[this._numMeshes] = debugMesh;
  80243. if (this._numMeshes === 0) {
  80244. this._renderFunction = this._updateDebugMeshes.bind(this);
  80245. this._scene.registerBeforeRender(this._renderFunction);
  80246. }
  80247. this._numMeshes++;
  80248. }
  80249. };
  80250. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  80251. if (!impostor || !this._scene) {
  80252. return;
  80253. }
  80254. var removed = false;
  80255. for (var i = 0; i < this._numMeshes; i++) {
  80256. if (this._impostors[i] == impostor) {
  80257. var mesh = this._meshes[i];
  80258. if (!mesh) {
  80259. continue;
  80260. }
  80261. this._scene.removeMesh(mesh);
  80262. mesh.dispose();
  80263. this._numMeshes--;
  80264. if (this._numMeshes > 0) {
  80265. this._meshes[i] = this._meshes[this._numMeshes];
  80266. this._impostors[i] = this._impostors[this._numMeshes];
  80267. this._meshes[this._numMeshes] = null;
  80268. this._impostors[this._numMeshes] = null;
  80269. }
  80270. else {
  80271. this._meshes[0] = null;
  80272. this._impostors[0] = null;
  80273. }
  80274. removed = true;
  80275. break;
  80276. }
  80277. }
  80278. if (removed && this._numMeshes === 0) {
  80279. this._scene.unregisterBeforeRender(this._renderFunction);
  80280. }
  80281. };
  80282. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  80283. if (!this._debugMaterial) {
  80284. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  80285. this._debugMaterial.wireframe = true;
  80286. }
  80287. return this._debugMaterial;
  80288. };
  80289. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  80290. if (!this._debugBoxMesh) {
  80291. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  80292. this._debugBoxMesh.renderingGroupId = 1;
  80293. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80294. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  80295. scene.removeMesh(this._debugBoxMesh);
  80296. }
  80297. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  80298. };
  80299. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  80300. if (!this._debugSphereMesh) {
  80301. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  80302. this._debugSphereMesh.renderingGroupId = 1;
  80303. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80304. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  80305. scene.removeMesh(this._debugSphereMesh);
  80306. }
  80307. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  80308. };
  80309. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  80310. var mesh = null;
  80311. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  80312. mesh = this._getDebugBoxMesh(scene);
  80313. impostor.getBoxSizeToRef(mesh.scaling);
  80314. }
  80315. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  80316. mesh = this._getDebugSphereMesh(scene);
  80317. var radius = impostor.getRadius();
  80318. mesh.scaling.x = radius * 2;
  80319. mesh.scaling.y = radius * 2;
  80320. mesh.scaling.z = radius * 2;
  80321. }
  80322. return mesh;
  80323. };
  80324. PhysicsViewer.prototype.dispose = function () {
  80325. for (var i = 0; i < this._numMeshes; i++) {
  80326. this.hideImpostor(this._impostors[i]);
  80327. }
  80328. if (this._debugBoxMesh) {
  80329. this._debugBoxMesh.dispose();
  80330. }
  80331. if (this._debugSphereMesh) {
  80332. this._debugSphereMesh.dispose();
  80333. }
  80334. if (this._debugMaterial) {
  80335. this._debugMaterial.dispose();
  80336. }
  80337. this._impostors.length = 0;
  80338. this._scene = null;
  80339. this._physicsEnginePlugin = null;
  80340. };
  80341. return PhysicsViewer;
  80342. }());
  80343. Debug.SkeletonViewer = /** @class */ (function () {
  80344. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  80345. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  80346. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  80347. this.skeleton = skeleton;
  80348. this.mesh = mesh;
  80349. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  80350. this.renderingGroupId = renderingGroupId;
  80351. this.color = BABYLON.Color3.White();
  80352. this._debugLines = new Array();
  80353. this._isEnabled = false;
  80354. this._scene = scene;
  80355. this.update();
  80356. this._renderFunction = this.update.bind(this);
  80357. }
  80358. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  80359. get: function () {
  80360. return this._isEnabled;
  80361. },
  80362. set: function (value) {
  80363. if (this._isEnabled === value) {
  80364. return;
  80365. }
  80366. this._isEnabled = value;
  80367. if (value) {
  80368. this._scene.registerBeforeRender(this._renderFunction);
  80369. }
  80370. else {
  80371. this._scene.unregisterBeforeRender(this._renderFunction);
  80372. }
  80373. },
  80374. enumerable: true,
  80375. configurable: true
  80376. });
  80377. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  80378. if (x === void 0) { x = 0; }
  80379. if (y === void 0) { y = 0; }
  80380. if (z === void 0) { z = 0; }
  80381. var tmat = BABYLON.Tmp.Matrix[0];
  80382. var parentBone = bone.getParent();
  80383. tmat.copyFrom(bone.getLocalMatrix());
  80384. if (x !== 0 || y !== 0 || z !== 0) {
  80385. var tmat2 = BABYLON.Tmp.Matrix[1];
  80386. BABYLON.Matrix.IdentityToRef(tmat2);
  80387. tmat2.m[12] = x;
  80388. tmat2.m[13] = y;
  80389. tmat2.m[14] = z;
  80390. tmat2.multiplyToRef(tmat, tmat);
  80391. }
  80392. if (parentBone) {
  80393. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  80394. }
  80395. tmat.multiplyToRef(meshMat, tmat);
  80396. position.x = tmat.m[12];
  80397. position.y = tmat.m[13];
  80398. position.z = tmat.m[14];
  80399. };
  80400. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  80401. var len = bones.length;
  80402. var meshPos = this.mesh.position;
  80403. for (var i = 0; i < len; i++) {
  80404. var bone = bones[i];
  80405. var points = this._debugLines[i];
  80406. if (!points) {
  80407. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80408. this._debugLines[i] = points;
  80409. }
  80410. this._getBonePosition(points[0], bone, meshMat);
  80411. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  80412. points[0].subtractInPlace(meshPos);
  80413. points[1].subtractInPlace(meshPos);
  80414. }
  80415. };
  80416. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  80417. var len = bones.length;
  80418. var boneNum = 0;
  80419. var meshPos = this.mesh.position;
  80420. for (var i = len - 1; i >= 0; i--) {
  80421. var childBone = bones[i];
  80422. var parentBone = childBone.getParent();
  80423. if (!parentBone) {
  80424. continue;
  80425. }
  80426. var points = this._debugLines[boneNum];
  80427. if (!points) {
  80428. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80429. this._debugLines[boneNum] = points;
  80430. }
  80431. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  80432. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  80433. points[0].subtractInPlace(meshPos);
  80434. points[1].subtractInPlace(meshPos);
  80435. boneNum++;
  80436. }
  80437. };
  80438. SkeletonViewer.prototype.update = function () {
  80439. if (this.autoUpdateBonesMatrices) {
  80440. this.skeleton.computeAbsoluteTransforms();
  80441. }
  80442. if (this.skeleton.bones[0].length === undefined) {
  80443. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80444. }
  80445. else {
  80446. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80447. }
  80448. if (!this._debugMesh) {
  80449. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  80450. this._debugMesh.renderingGroupId = this.renderingGroupId;
  80451. }
  80452. else {
  80453. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  80454. }
  80455. this._debugMesh.position.copyFrom(this.mesh.position);
  80456. this._debugMesh.color = this.color;
  80457. };
  80458. SkeletonViewer.prototype.dispose = function () {
  80459. if (this._debugMesh) {
  80460. this.isEnabled = false;
  80461. this._debugMesh.dispose();
  80462. this._debugMesh = null;
  80463. }
  80464. };
  80465. return SkeletonViewer;
  80466. }());
  80467. return Debug;
  80468. }());
  80469. BABYLON.Debug = Debug;
  80470. })(BABYLON || (BABYLON = {}));
  80471. //# sourceMappingURL=babylon.debugModules.js.map
  80472. "use strict";
  80473. var BABYLON;
  80474. (function (BABYLON) {
  80475. var RayHelper = /** @class */ (function () {
  80476. function RayHelper(ray) {
  80477. this.ray = ray;
  80478. }
  80479. RayHelper.CreateAndShow = function (ray, scene, color) {
  80480. var helper = new RayHelper(ray);
  80481. helper.show(scene, color);
  80482. return helper;
  80483. };
  80484. RayHelper.prototype.show = function (scene, color) {
  80485. if (!this._renderFunction && this.ray) {
  80486. var ray = this.ray;
  80487. this._renderFunction = this._render.bind(this);
  80488. this._scene = scene;
  80489. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  80490. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  80491. if (this._renderFunction) {
  80492. this._scene.registerBeforeRender(this._renderFunction);
  80493. }
  80494. }
  80495. if (color && this._renderLine) {
  80496. this._renderLine.color.copyFrom(color);
  80497. }
  80498. };
  80499. RayHelper.prototype.hide = function () {
  80500. if (this._renderFunction && this._scene) {
  80501. this._scene.unregisterBeforeRender(this._renderFunction);
  80502. this._scene = null;
  80503. this._renderFunction = null;
  80504. if (this._renderLine) {
  80505. this._renderLine.dispose();
  80506. this._renderLine = null;
  80507. }
  80508. this._renderPoints = [];
  80509. }
  80510. };
  80511. RayHelper.prototype._render = function () {
  80512. var ray = this.ray;
  80513. if (!ray) {
  80514. return;
  80515. }
  80516. var point = this._renderPoints[1];
  80517. var len = Math.min(ray.length, 1000000);
  80518. point.copyFrom(ray.direction);
  80519. point.scaleInPlace(len);
  80520. point.addInPlace(ray.origin);
  80521. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  80522. };
  80523. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  80524. this._attachedToMesh = mesh;
  80525. var ray = this.ray;
  80526. if (!ray) {
  80527. return;
  80528. }
  80529. if (!ray.direction) {
  80530. ray.direction = BABYLON.Vector3.Zero();
  80531. }
  80532. if (!ray.origin) {
  80533. ray.origin = BABYLON.Vector3.Zero();
  80534. }
  80535. if (length) {
  80536. ray.length = length;
  80537. }
  80538. if (!meshSpaceOrigin) {
  80539. meshSpaceOrigin = BABYLON.Vector3.Zero();
  80540. }
  80541. if (!meshSpaceDirection) {
  80542. // -1 so that this will work with Mesh.lookAt
  80543. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  80544. }
  80545. if (!this._meshSpaceDirection) {
  80546. this._meshSpaceDirection = meshSpaceDirection.clone();
  80547. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  80548. }
  80549. else {
  80550. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  80551. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  80552. }
  80553. if (!this._updateToMeshFunction) {
  80554. this._updateToMeshFunction = this._updateToMesh.bind(this);
  80555. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  80556. }
  80557. this._updateToMesh();
  80558. };
  80559. RayHelper.prototype.detachFromMesh = function () {
  80560. if (this._attachedToMesh) {
  80561. if (this._updateToMeshFunction) {
  80562. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  80563. }
  80564. this._attachedToMesh = null;
  80565. this._updateToMeshFunction = null;
  80566. }
  80567. };
  80568. RayHelper.prototype._updateToMesh = function () {
  80569. var ray = this.ray;
  80570. if (!this._attachedToMesh || !ray) {
  80571. return;
  80572. }
  80573. if (this._attachedToMesh._isDisposed) {
  80574. this.detachFromMesh();
  80575. return;
  80576. }
  80577. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  80578. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  80579. };
  80580. RayHelper.prototype.dispose = function () {
  80581. this.hide();
  80582. this.detachFromMesh();
  80583. this.ray = null;
  80584. };
  80585. return RayHelper;
  80586. }());
  80587. BABYLON.RayHelper = RayHelper;
  80588. })(BABYLON || (BABYLON = {}));
  80589. //# sourceMappingURL=babylon.rayHelper.js.map
  80590. "use strict";
  80591. var BABYLON;
  80592. (function (BABYLON) {
  80593. // load the inspector using require, if not present in the global namespace.
  80594. var DebugLayer = /** @class */ (function () {
  80595. function DebugLayer(scene) {
  80596. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80597. this._scene = scene;
  80598. // load inspector using require, if it doesn't exist on the global namespace.
  80599. }
  80600. /** Creates the inspector window. */
  80601. DebugLayer.prototype._createInspector = function (config) {
  80602. if (config === void 0) { config = {}; }
  80603. var popup = config.popup || false;
  80604. var initialTab = config.initialTab || 0;
  80605. var parentElement = config.parentElement || null;
  80606. if (!this._inspector) {
  80607. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80608. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  80609. } // else nothing to do,; instance is already existing
  80610. };
  80611. DebugLayer.prototype.isVisible = function () {
  80612. if (!this._inspector) {
  80613. return false;
  80614. }
  80615. return true;
  80616. };
  80617. DebugLayer.prototype.hide = function () {
  80618. if (this._inspector) {
  80619. try {
  80620. this._inspector.dispose();
  80621. }
  80622. catch (e) {
  80623. // If the inspector has been removed directly from the inspector tool
  80624. }
  80625. this._inspector = null;
  80626. }
  80627. };
  80628. DebugLayer.prototype.show = function (config) {
  80629. if (config === void 0) { config = {}; }
  80630. if (typeof this.BJSINSPECTOR == 'undefined') {
  80631. // Load inspector and add it to the DOM
  80632. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  80633. }
  80634. else {
  80635. // Otherwise creates the inspector
  80636. this._createInspector(config);
  80637. }
  80638. };
  80639. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  80640. return DebugLayer;
  80641. }());
  80642. BABYLON.DebugLayer = DebugLayer;
  80643. })(BABYLON || (BABYLON = {}));
  80644. //# sourceMappingURL=babylon.debugLayer.js.map
  80645. "use strict";
  80646. var BABYLON;
  80647. (function (BABYLON) {
  80648. var BoundingBoxRenderer = /** @class */ (function () {
  80649. function BoundingBoxRenderer(scene) {
  80650. this.frontColor = new BABYLON.Color3(1, 1, 1);
  80651. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  80652. this.showBackLines = true;
  80653. this.renderList = new BABYLON.SmartArray(32);
  80654. this._vertexBuffers = {};
  80655. this._scene = scene;
  80656. }
  80657. BoundingBoxRenderer.prototype._prepareRessources = function () {
  80658. if (this._colorShader) {
  80659. return;
  80660. }
  80661. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  80662. attributes: [BABYLON.VertexBuffer.PositionKind],
  80663. uniforms: ["world", "viewProjection", "color"]
  80664. });
  80665. var engine = this._scene.getEngine();
  80666. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  80667. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  80668. this._createIndexBuffer();
  80669. };
  80670. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  80671. var engine = this._scene.getEngine();
  80672. 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]);
  80673. };
  80674. BoundingBoxRenderer.prototype._rebuild = function () {
  80675. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80676. if (vb) {
  80677. vb._rebuild();
  80678. }
  80679. this._createIndexBuffer();
  80680. };
  80681. BoundingBoxRenderer.prototype.reset = function () {
  80682. this.renderList.reset();
  80683. };
  80684. BoundingBoxRenderer.prototype.render = function () {
  80685. if (this.renderList.length === 0) {
  80686. return;
  80687. }
  80688. this._prepareRessources();
  80689. if (!this._colorShader.isReady()) {
  80690. return;
  80691. }
  80692. var engine = this._scene.getEngine();
  80693. engine.setDepthWrite(false);
  80694. this._colorShader._preBind();
  80695. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  80696. var boundingBox = this.renderList.data[boundingBoxIndex];
  80697. var min = boundingBox.minimum;
  80698. var max = boundingBox.maximum;
  80699. var diff = max.subtract(min);
  80700. var median = min.add(diff.scale(0.5));
  80701. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80702. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80703. .multiply(boundingBox.getWorldMatrix());
  80704. // VBOs
  80705. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80706. if (this.showBackLines) {
  80707. // Back
  80708. engine.setDepthFunctionToGreaterOrEqual();
  80709. this._scene.resetCachedMaterial();
  80710. this._colorShader.setColor4("color", this.backColor.toColor4());
  80711. this._colorShader.bind(worldMatrix);
  80712. // Draw order
  80713. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80714. }
  80715. // Front
  80716. engine.setDepthFunctionToLess();
  80717. this._scene.resetCachedMaterial();
  80718. this._colorShader.setColor4("color", this.frontColor.toColor4());
  80719. this._colorShader.bind(worldMatrix);
  80720. // Draw order
  80721. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80722. }
  80723. this._colorShader.unbind();
  80724. engine.setDepthFunctionToLessOrEqual();
  80725. engine.setDepthWrite(true);
  80726. };
  80727. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  80728. this._prepareRessources();
  80729. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  80730. return;
  80731. }
  80732. var engine = this._scene.getEngine();
  80733. engine.setDepthWrite(false);
  80734. engine.setColorWrite(false);
  80735. this._colorShader._preBind();
  80736. var boundingBox = mesh._boundingInfo.boundingBox;
  80737. var min = boundingBox.minimum;
  80738. var max = boundingBox.maximum;
  80739. var diff = max.subtract(min);
  80740. var median = min.add(diff.scale(0.5));
  80741. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80742. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80743. .multiply(boundingBox.getWorldMatrix());
  80744. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80745. engine.setDepthFunctionToLess();
  80746. this._scene.resetCachedMaterial();
  80747. this._colorShader.bind(worldMatrix);
  80748. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80749. this._colorShader.unbind();
  80750. engine.setDepthFunctionToLessOrEqual();
  80751. engine.setDepthWrite(true);
  80752. engine.setColorWrite(true);
  80753. };
  80754. BoundingBoxRenderer.prototype.dispose = function () {
  80755. if (!this._colorShader) {
  80756. return;
  80757. }
  80758. this.renderList.dispose();
  80759. this._colorShader.dispose();
  80760. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80761. if (buffer) {
  80762. buffer.dispose();
  80763. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80764. }
  80765. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80766. };
  80767. return BoundingBoxRenderer;
  80768. }());
  80769. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  80770. })(BABYLON || (BABYLON = {}));
  80771. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  80772. "use strict";
  80773. var BABYLON;
  80774. (function (BABYLON) {
  80775. var MorphTarget = /** @class */ (function () {
  80776. function MorphTarget(name, influence) {
  80777. if (influence === void 0) { influence = 0; }
  80778. this.name = name;
  80779. this.animations = new Array();
  80780. this._positions = null;
  80781. this._normals = null;
  80782. this._tangents = null;
  80783. this.onInfluenceChanged = new BABYLON.Observable();
  80784. this.influence = influence;
  80785. }
  80786. Object.defineProperty(MorphTarget.prototype, "influence", {
  80787. get: function () {
  80788. return this._influence;
  80789. },
  80790. set: function (influence) {
  80791. if (this._influence === influence) {
  80792. return;
  80793. }
  80794. var previous = this._influence;
  80795. this._influence = influence;
  80796. if (this.onInfluenceChanged.hasObservers) {
  80797. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  80798. }
  80799. },
  80800. enumerable: true,
  80801. configurable: true
  80802. });
  80803. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  80804. get: function () {
  80805. return !!this._positions;
  80806. },
  80807. enumerable: true,
  80808. configurable: true
  80809. });
  80810. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  80811. get: function () {
  80812. return !!this._normals;
  80813. },
  80814. enumerable: true,
  80815. configurable: true
  80816. });
  80817. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  80818. get: function () {
  80819. return !!this._tangents;
  80820. },
  80821. enumerable: true,
  80822. configurable: true
  80823. });
  80824. MorphTarget.prototype.setPositions = function (data) {
  80825. this._positions = data;
  80826. };
  80827. MorphTarget.prototype.getPositions = function () {
  80828. return this._positions;
  80829. };
  80830. MorphTarget.prototype.setNormals = function (data) {
  80831. this._normals = data;
  80832. };
  80833. MorphTarget.prototype.getNormals = function () {
  80834. return this._normals;
  80835. };
  80836. MorphTarget.prototype.setTangents = function (data) {
  80837. this._tangents = data;
  80838. };
  80839. MorphTarget.prototype.getTangents = function () {
  80840. return this._tangents;
  80841. };
  80842. /**
  80843. * Serializes the current target into a Serialization object.
  80844. * Returns the serialized object.
  80845. */
  80846. MorphTarget.prototype.serialize = function () {
  80847. var serializationObject = {};
  80848. serializationObject.name = this.name;
  80849. serializationObject.influence = this.influence;
  80850. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  80851. if (this.hasNormals) {
  80852. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  80853. }
  80854. if (this.hasTangents) {
  80855. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  80856. }
  80857. // Animations
  80858. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  80859. return serializationObject;
  80860. };
  80861. // Statics
  80862. MorphTarget.Parse = function (serializationObject) {
  80863. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  80864. result.setPositions(serializationObject.positions);
  80865. if (serializationObject.normals) {
  80866. result.setNormals(serializationObject.normals);
  80867. }
  80868. if (serializationObject.tangents) {
  80869. result.setTangents(serializationObject.tangents);
  80870. }
  80871. // Animations
  80872. if (serializationObject.animations) {
  80873. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  80874. var parsedAnimation = serializationObject.animations[animationIndex];
  80875. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  80876. }
  80877. }
  80878. return result;
  80879. };
  80880. MorphTarget.FromMesh = function (mesh, name, influence) {
  80881. if (!name) {
  80882. name = mesh.name;
  80883. }
  80884. var result = new MorphTarget(name, influence);
  80885. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  80886. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  80887. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  80888. }
  80889. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  80890. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  80891. }
  80892. return result;
  80893. };
  80894. return MorphTarget;
  80895. }());
  80896. BABYLON.MorphTarget = MorphTarget;
  80897. })(BABYLON || (BABYLON = {}));
  80898. //# sourceMappingURL=babylon.morphTarget.js.map
  80899. "use strict";
  80900. var BABYLON;
  80901. (function (BABYLON) {
  80902. var MorphTargetManager = /** @class */ (function () {
  80903. function MorphTargetManager(scene) {
  80904. if (scene === void 0) { scene = null; }
  80905. this._targets = new Array();
  80906. this._targetObservable = new Array();
  80907. this._activeTargets = new BABYLON.SmartArray(16);
  80908. this._supportsNormals = false;
  80909. this._supportsTangents = false;
  80910. this._vertexCount = 0;
  80911. this._uniqueId = 0;
  80912. this._tempInfluences = new Array();
  80913. if (!scene) {
  80914. scene = BABYLON.Engine.LastCreatedScene;
  80915. }
  80916. this._scene = scene;
  80917. if (this._scene) {
  80918. this._scene.morphTargetManagers.push(this);
  80919. this._uniqueId = this._scene.getUniqueId();
  80920. }
  80921. }
  80922. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  80923. get: function () {
  80924. return this._uniqueId;
  80925. },
  80926. enumerable: true,
  80927. configurable: true
  80928. });
  80929. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  80930. get: function () {
  80931. return this._vertexCount;
  80932. },
  80933. enumerable: true,
  80934. configurable: true
  80935. });
  80936. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  80937. get: function () {
  80938. return this._supportsNormals;
  80939. },
  80940. enumerable: true,
  80941. configurable: true
  80942. });
  80943. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  80944. get: function () {
  80945. return this._supportsTangents;
  80946. },
  80947. enumerable: true,
  80948. configurable: true
  80949. });
  80950. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  80951. get: function () {
  80952. return this._targets.length;
  80953. },
  80954. enumerable: true,
  80955. configurable: true
  80956. });
  80957. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  80958. get: function () {
  80959. return this._activeTargets.length;
  80960. },
  80961. enumerable: true,
  80962. configurable: true
  80963. });
  80964. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  80965. get: function () {
  80966. return this._influences;
  80967. },
  80968. enumerable: true,
  80969. configurable: true
  80970. });
  80971. MorphTargetManager.prototype.getActiveTarget = function (index) {
  80972. return this._activeTargets.data[index];
  80973. };
  80974. MorphTargetManager.prototype.getTarget = function (index) {
  80975. return this._targets[index];
  80976. };
  80977. MorphTargetManager.prototype.addTarget = function (target) {
  80978. var _this = this;
  80979. this._targets.push(target);
  80980. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  80981. _this._syncActiveTargets(needUpdate);
  80982. }));
  80983. this._syncActiveTargets(true);
  80984. };
  80985. MorphTargetManager.prototype.removeTarget = function (target) {
  80986. var index = this._targets.indexOf(target);
  80987. if (index >= 0) {
  80988. this._targets.splice(index, 1);
  80989. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  80990. this._syncActiveTargets(true);
  80991. }
  80992. };
  80993. /**
  80994. * Serializes the current manager into a Serialization object.
  80995. * Returns the serialized object.
  80996. */
  80997. MorphTargetManager.prototype.serialize = function () {
  80998. var serializationObject = {};
  80999. serializationObject.id = this.uniqueId;
  81000. serializationObject.targets = [];
  81001. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81002. var target = _a[_i];
  81003. serializationObject.targets.push(target.serialize());
  81004. }
  81005. return serializationObject;
  81006. };
  81007. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  81008. var influenceCount = 0;
  81009. this._activeTargets.reset();
  81010. this._supportsNormals = true;
  81011. this._supportsTangents = true;
  81012. this._vertexCount = 0;
  81013. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81014. var target = _a[_i];
  81015. this._activeTargets.push(target);
  81016. this._tempInfluences[influenceCount++] = target.influence;
  81017. var positions = target.getPositions();
  81018. if (positions) {
  81019. this._supportsNormals = this._supportsNormals && target.hasNormals;
  81020. this._supportsTangents = this._supportsTangents && target.hasTangents;
  81021. var vertexCount = positions.length / 3;
  81022. if (this._vertexCount === 0) {
  81023. this._vertexCount = vertexCount;
  81024. }
  81025. else if (this._vertexCount !== vertexCount) {
  81026. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  81027. return;
  81028. }
  81029. }
  81030. }
  81031. if (!this._influences || this._influences.length !== influenceCount) {
  81032. this._influences = new Float32Array(influenceCount);
  81033. }
  81034. for (var index = 0; index < influenceCount; index++) {
  81035. this._influences[index] = this._tempInfluences[index];
  81036. }
  81037. if (needUpdate && this._scene) {
  81038. // Flag meshes as dirty to resync with the active targets
  81039. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  81040. var mesh = _c[_b];
  81041. if (mesh.morphTargetManager === this) {
  81042. mesh._syncGeometryWithMorphTargetManager();
  81043. }
  81044. }
  81045. }
  81046. };
  81047. // Statics
  81048. MorphTargetManager.Parse = function (serializationObject, scene) {
  81049. var result = new MorphTargetManager(scene);
  81050. result._uniqueId = serializationObject.id;
  81051. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  81052. var targetData = _a[_i];
  81053. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  81054. }
  81055. return result;
  81056. };
  81057. return MorphTargetManager;
  81058. }());
  81059. BABYLON.MorphTargetManager = MorphTargetManager;
  81060. })(BABYLON || (BABYLON = {}));
  81061. //# sourceMappingURL=babylon.morphTargetManager.js.map
  81062. "use strict";
  81063. var BABYLON;
  81064. (function (BABYLON) {
  81065. var Octree = /** @class */ (function () {
  81066. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  81067. if (maxDepth === void 0) { maxDepth = 2; }
  81068. this.maxDepth = maxDepth;
  81069. this.dynamicContent = new Array();
  81070. this._maxBlockCapacity = maxBlockCapacity || 64;
  81071. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  81072. this._creationFunc = creationFunc;
  81073. }
  81074. // Methods
  81075. Octree.prototype.update = function (worldMin, worldMax, entries) {
  81076. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  81077. };
  81078. Octree.prototype.addMesh = function (entry) {
  81079. for (var index = 0; index < this.blocks.length; index++) {
  81080. var block = this.blocks[index];
  81081. block.addEntry(entry);
  81082. }
  81083. };
  81084. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  81085. this._selectionContent.reset();
  81086. for (var index = 0; index < this.blocks.length; index++) {
  81087. var block = this.blocks[index];
  81088. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  81089. }
  81090. if (allowDuplicate) {
  81091. this._selectionContent.concat(this.dynamicContent);
  81092. }
  81093. else {
  81094. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81095. }
  81096. return this._selectionContent;
  81097. };
  81098. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  81099. this._selectionContent.reset();
  81100. for (var index = 0; index < this.blocks.length; index++) {
  81101. var block = this.blocks[index];
  81102. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  81103. }
  81104. if (allowDuplicate) {
  81105. this._selectionContent.concat(this.dynamicContent);
  81106. }
  81107. else {
  81108. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81109. }
  81110. return this._selectionContent;
  81111. };
  81112. Octree.prototype.intersectsRay = function (ray) {
  81113. this._selectionContent.reset();
  81114. for (var index = 0; index < this.blocks.length; index++) {
  81115. var block = this.blocks[index];
  81116. block.intersectsRay(ray, this._selectionContent);
  81117. }
  81118. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81119. return this._selectionContent;
  81120. };
  81121. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  81122. target.blocks = new Array();
  81123. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  81124. // Segmenting space
  81125. for (var x = 0; x < 2; x++) {
  81126. for (var y = 0; y < 2; y++) {
  81127. for (var z = 0; z < 2; z++) {
  81128. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  81129. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  81130. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  81131. block.addEntries(entries);
  81132. target.blocks.push(block);
  81133. }
  81134. }
  81135. }
  81136. };
  81137. Octree.CreationFuncForMeshes = function (entry, block) {
  81138. var boundingInfo = entry.getBoundingInfo();
  81139. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81140. block.entries.push(entry);
  81141. }
  81142. };
  81143. Octree.CreationFuncForSubMeshes = function (entry, block) {
  81144. var boundingInfo = entry.getBoundingInfo();
  81145. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81146. block.entries.push(entry);
  81147. }
  81148. };
  81149. return Octree;
  81150. }());
  81151. BABYLON.Octree = Octree;
  81152. })(BABYLON || (BABYLON = {}));
  81153. //# sourceMappingURL=babylon.octree.js.map
  81154. "use strict";
  81155. var BABYLON;
  81156. (function (BABYLON) {
  81157. var OctreeBlock = /** @class */ (function () {
  81158. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  81159. this.entries = new Array();
  81160. this._boundingVectors = new Array();
  81161. this._capacity = capacity;
  81162. this._depth = depth;
  81163. this._maxDepth = maxDepth;
  81164. this._creationFunc = creationFunc;
  81165. this._minPoint = minPoint;
  81166. this._maxPoint = maxPoint;
  81167. this._boundingVectors.push(minPoint.clone());
  81168. this._boundingVectors.push(maxPoint.clone());
  81169. this._boundingVectors.push(minPoint.clone());
  81170. this._boundingVectors[2].x = maxPoint.x;
  81171. this._boundingVectors.push(minPoint.clone());
  81172. this._boundingVectors[3].y = maxPoint.y;
  81173. this._boundingVectors.push(minPoint.clone());
  81174. this._boundingVectors[4].z = maxPoint.z;
  81175. this._boundingVectors.push(maxPoint.clone());
  81176. this._boundingVectors[5].z = minPoint.z;
  81177. this._boundingVectors.push(maxPoint.clone());
  81178. this._boundingVectors[6].x = minPoint.x;
  81179. this._boundingVectors.push(maxPoint.clone());
  81180. this._boundingVectors[7].y = minPoint.y;
  81181. }
  81182. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  81183. // Property
  81184. get: function () {
  81185. return this._capacity;
  81186. },
  81187. enumerable: true,
  81188. configurable: true
  81189. });
  81190. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  81191. get: function () {
  81192. return this._minPoint;
  81193. },
  81194. enumerable: true,
  81195. configurable: true
  81196. });
  81197. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  81198. get: function () {
  81199. return this._maxPoint;
  81200. },
  81201. enumerable: true,
  81202. configurable: true
  81203. });
  81204. // Methods
  81205. OctreeBlock.prototype.addEntry = function (entry) {
  81206. if (this.blocks) {
  81207. for (var index = 0; index < this.blocks.length; index++) {
  81208. var block = this.blocks[index];
  81209. block.addEntry(entry);
  81210. }
  81211. return;
  81212. }
  81213. this._creationFunc(entry, this);
  81214. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  81215. this.createInnerBlocks();
  81216. }
  81217. };
  81218. OctreeBlock.prototype.addEntries = function (entries) {
  81219. for (var index = 0; index < entries.length; index++) {
  81220. var mesh = entries[index];
  81221. this.addEntry(mesh);
  81222. }
  81223. };
  81224. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  81225. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  81226. if (this.blocks) {
  81227. for (var index = 0; index < this.blocks.length; index++) {
  81228. var block = this.blocks[index];
  81229. block.select(frustumPlanes, selection, allowDuplicate);
  81230. }
  81231. return;
  81232. }
  81233. if (allowDuplicate) {
  81234. selection.concat(this.entries);
  81235. }
  81236. else {
  81237. selection.concatWithNoDuplicate(this.entries);
  81238. }
  81239. }
  81240. };
  81241. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  81242. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  81243. if (this.blocks) {
  81244. for (var index = 0; index < this.blocks.length; index++) {
  81245. var block = this.blocks[index];
  81246. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  81247. }
  81248. return;
  81249. }
  81250. if (allowDuplicate) {
  81251. selection.concat(this.entries);
  81252. }
  81253. else {
  81254. selection.concatWithNoDuplicate(this.entries);
  81255. }
  81256. }
  81257. };
  81258. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  81259. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  81260. if (this.blocks) {
  81261. for (var index = 0; index < this.blocks.length; index++) {
  81262. var block = this.blocks[index];
  81263. block.intersectsRay(ray, selection);
  81264. }
  81265. return;
  81266. }
  81267. selection.concatWithNoDuplicate(this.entries);
  81268. }
  81269. };
  81270. OctreeBlock.prototype.createInnerBlocks = function () {
  81271. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  81272. };
  81273. return OctreeBlock;
  81274. }());
  81275. BABYLON.OctreeBlock = OctreeBlock;
  81276. })(BABYLON || (BABYLON = {}));
  81277. //# sourceMappingURL=babylon.octreeBlock.js.map
  81278. "use strict";
  81279. var BABYLON;
  81280. (function (BABYLON) {
  81281. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  81282. __extends(VRDistortionCorrectionPostProcess, _super);
  81283. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  81284. var _this = _super.call(this, name, "vrDistortionCorrection", [
  81285. 'LensCenter',
  81286. 'Scale',
  81287. 'ScaleIn',
  81288. 'HmdWarpParam'
  81289. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  81290. _this._isRightEye = isRightEye;
  81291. _this._distortionFactors = vrMetrics.distortionK;
  81292. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  81293. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  81294. _this.adaptScaleToCurrentViewport = true;
  81295. _this.onSizeChangedObservable.add(function () {
  81296. _this.aspectRatio = _this.width * .5 / _this.height;
  81297. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  81298. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  81299. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  81300. });
  81301. _this.onApplyObservable.add(function (effect) {
  81302. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  81303. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  81304. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  81305. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  81306. });
  81307. return _this;
  81308. }
  81309. return VRDistortionCorrectionPostProcess;
  81310. }(BABYLON.PostProcess));
  81311. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  81312. })(BABYLON || (BABYLON = {}));
  81313. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  81314. "use strict";
  81315. var BABYLON;
  81316. (function (BABYLON) {
  81317. var AnaglyphPostProcess = /** @class */ (function (_super) {
  81318. __extends(AnaglyphPostProcess, _super);
  81319. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  81320. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  81321. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81322. _this.onApplyObservable.add(function (effect) {
  81323. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  81324. });
  81325. return _this;
  81326. }
  81327. return AnaglyphPostProcess;
  81328. }(BABYLON.PostProcess));
  81329. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  81330. })(BABYLON || (BABYLON = {}));
  81331. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  81332. "use strict";
  81333. var BABYLON;
  81334. (function (BABYLON) {
  81335. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  81336. __extends(StereoscopicInterlacePostProcess, _super);
  81337. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  81338. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  81339. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81340. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81341. _this.onSizeChangedObservable.add(function () {
  81342. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81343. });
  81344. _this.onApplyObservable.add(function (effect) {
  81345. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  81346. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  81347. });
  81348. return _this;
  81349. }
  81350. return StereoscopicInterlacePostProcess;
  81351. }(BABYLON.PostProcess));
  81352. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  81353. })(BABYLON || (BABYLON = {}));
  81354. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  81355. "use strict";
  81356. var BABYLON;
  81357. (function (BABYLON) {
  81358. /**
  81359. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  81360. * Screen rotation is taken into account.
  81361. */
  81362. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  81363. function FreeCameraDeviceOrientationInput() {
  81364. var _this = this;
  81365. this._screenOrientationAngle = 0;
  81366. this._screenQuaternion = new BABYLON.Quaternion();
  81367. this._alpha = 0;
  81368. this._beta = 0;
  81369. this._gamma = 0;
  81370. this._orientationChanged = function () {
  81371. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  81372. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  81373. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  81374. };
  81375. this._deviceOrientation = function (evt) {
  81376. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  81377. _this._beta = evt.beta !== null ? evt.beta : 0;
  81378. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  81379. };
  81380. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  81381. this._orientationChanged();
  81382. }
  81383. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  81384. get: function () {
  81385. return this._camera;
  81386. },
  81387. set: function (camera) {
  81388. this._camera = camera;
  81389. if (this._camera != null && !this._camera.rotationQuaternion) {
  81390. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  81391. }
  81392. },
  81393. enumerable: true,
  81394. configurable: true
  81395. });
  81396. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81397. window.addEventListener("orientationchange", this._orientationChanged);
  81398. window.addEventListener("deviceorientation", this._deviceOrientation);
  81399. //In certain cases, the attach control is called AFTER orientation was changed,
  81400. //So this is needed.
  81401. this._orientationChanged();
  81402. };
  81403. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  81404. window.removeEventListener("orientationchange", this._orientationChanged);
  81405. window.removeEventListener("deviceorientation", this._deviceOrientation);
  81406. };
  81407. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  81408. //if no device orientation provided, don't update the rotation.
  81409. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  81410. if (!this._alpha)
  81411. return;
  81412. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  81413. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  81414. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  81415. //Mirror on XY Plane
  81416. this._camera.rotationQuaternion.z *= -1;
  81417. this._camera.rotationQuaternion.w *= -1;
  81418. };
  81419. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  81420. return "FreeCameraDeviceOrientationInput";
  81421. };
  81422. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  81423. return "deviceOrientation";
  81424. };
  81425. return FreeCameraDeviceOrientationInput;
  81426. }());
  81427. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  81428. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  81429. })(BABYLON || (BABYLON = {}));
  81430. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  81431. "use strict";
  81432. var BABYLON;
  81433. (function (BABYLON) {
  81434. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  81435. function ArcRotateCameraVRDeviceOrientationInput() {
  81436. this.alphaCorrection = 1;
  81437. this.betaCorrection = 1;
  81438. this.gammaCorrection = 1;
  81439. this._alpha = 0;
  81440. this._gamma = 0;
  81441. this._dirty = false;
  81442. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  81443. }
  81444. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81445. this.camera.attachControl(element, noPreventDefault);
  81446. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  81447. };
  81448. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  81449. if (evt.alpha !== null) {
  81450. this._alpha = +evt.alpha | 0;
  81451. }
  81452. if (evt.gamma !== null) {
  81453. this._gamma = +evt.gamma | 0;
  81454. }
  81455. this._dirty = true;
  81456. };
  81457. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  81458. if (this._dirty) {
  81459. this._dirty = false;
  81460. if (this._gamma < 0) {
  81461. this._gamma = 180 + this._gamma;
  81462. }
  81463. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  81464. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  81465. }
  81466. };
  81467. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  81468. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  81469. };
  81470. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  81471. return "ArcRotateCameraVRDeviceOrientationInput";
  81472. };
  81473. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  81474. return "VRDeviceOrientation";
  81475. };
  81476. return ArcRotateCameraVRDeviceOrientationInput;
  81477. }());
  81478. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  81479. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  81480. })(BABYLON || (BABYLON = {}));
  81481. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  81482. "use strict";
  81483. var BABYLON;
  81484. (function (BABYLON) {
  81485. var VRCameraMetrics = /** @class */ (function () {
  81486. function VRCameraMetrics() {
  81487. this.compensateDistortion = true;
  81488. }
  81489. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  81490. get: function () {
  81491. return this.hResolution / (2 * this.vResolution);
  81492. },
  81493. enumerable: true,
  81494. configurable: true
  81495. });
  81496. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  81497. get: function () {
  81498. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  81499. },
  81500. enumerable: true,
  81501. configurable: true
  81502. });
  81503. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  81504. get: function () {
  81505. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81506. var h = (4 * meters) / this.hScreenSize;
  81507. return BABYLON.Matrix.Translation(h, 0, 0);
  81508. },
  81509. enumerable: true,
  81510. configurable: true
  81511. });
  81512. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  81513. get: function () {
  81514. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81515. var h = (4 * meters) / this.hScreenSize;
  81516. return BABYLON.Matrix.Translation(-h, 0, 0);
  81517. },
  81518. enumerable: true,
  81519. configurable: true
  81520. });
  81521. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  81522. get: function () {
  81523. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  81524. },
  81525. enumerable: true,
  81526. configurable: true
  81527. });
  81528. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  81529. get: function () {
  81530. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  81531. },
  81532. enumerable: true,
  81533. configurable: true
  81534. });
  81535. VRCameraMetrics.GetDefault = function () {
  81536. var result = new VRCameraMetrics();
  81537. result.hResolution = 1280;
  81538. result.vResolution = 800;
  81539. result.hScreenSize = 0.149759993;
  81540. result.vScreenSize = 0.0935999975;
  81541. result.vScreenCenter = 0.0467999987;
  81542. result.eyeToScreenDistance = 0.0410000011;
  81543. result.lensSeparationDistance = 0.0635000020;
  81544. result.interpupillaryDistance = 0.0640000030;
  81545. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  81546. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  81547. result.postProcessScaleFactor = 1.714605507808412;
  81548. result.lensCenterOffset = 0.151976421;
  81549. return result;
  81550. };
  81551. return VRCameraMetrics;
  81552. }());
  81553. BABYLON.VRCameraMetrics = VRCameraMetrics;
  81554. })(BABYLON || (BABYLON = {}));
  81555. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  81556. "use strict";
  81557. var BABYLON;
  81558. (function (BABYLON) {
  81559. /**
  81560. * This represents a WebVR camera.
  81561. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  81562. * @example http://doc.babylonjs.com/how_to/webvr_camera
  81563. */
  81564. var WebVRFreeCamera = /** @class */ (function (_super) {
  81565. __extends(WebVRFreeCamera, _super);
  81566. /**
  81567. * Instantiates a WebVRFreeCamera.
  81568. * @param name The name of the WebVRFreeCamera
  81569. * @param position The starting anchor position for the camera
  81570. * @param scene The scene the camera belongs to
  81571. * @param webVROptions a set of customizable options for the webVRCamera
  81572. */
  81573. function WebVRFreeCamera(name, position, scene, webVROptions) {
  81574. if (webVROptions === void 0) { webVROptions = {}; }
  81575. var _this = _super.call(this, name, position, scene) || this;
  81576. _this.webVROptions = webVROptions;
  81577. /**
  81578. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  81579. */
  81580. _this._vrDevice = null;
  81581. /**
  81582. * The rawPose of the vrDevice.
  81583. */
  81584. _this.rawPose = null;
  81585. _this._specsVersion = "1.1";
  81586. _this._attached = false;
  81587. _this._descendants = [];
  81588. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  81589. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  81590. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  81591. _this._standingMatrix = null;
  81592. /**
  81593. * Represents device position in babylon space.
  81594. */
  81595. _this.devicePosition = BABYLON.Vector3.Zero();
  81596. /**
  81597. * Represents device rotation in babylon space.
  81598. */
  81599. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  81600. /**
  81601. * The scale of the device to be used when translating from device space to babylon space.
  81602. */
  81603. _this.deviceScaleFactor = 1;
  81604. _this._deviceToWorld = BABYLON.Matrix.Identity();
  81605. _this._worldToDevice = BABYLON.Matrix.Identity();
  81606. /**
  81607. * References to the webVR controllers for the vrDevice.
  81608. */
  81609. _this.controllers = [];
  81610. /**
  81611. * Emits an event when a controller is attached.
  81612. */
  81613. _this.onControllersAttachedObservable = new BABYLON.Observable();
  81614. /**
  81615. * Emits an event when a controller's mesh has been loaded;
  81616. */
  81617. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81618. /**
  81619. * If the rig cameras be used as parent instead of this camera.
  81620. */
  81621. _this.rigParenting = true;
  81622. _this._defaultHeight = undefined;
  81623. _this._workingVector = BABYLON.Vector3.Zero();
  81624. _this._oneVector = BABYLON.Vector3.One();
  81625. _this._workingMatrix = BABYLON.Matrix.Identity();
  81626. _this._cache.position = BABYLON.Vector3.Zero();
  81627. if (webVROptions.defaultHeight) {
  81628. _this._defaultHeight = webVROptions.defaultHeight;
  81629. _this.position.y = _this._defaultHeight;
  81630. }
  81631. _this.minZ = 0.1;
  81632. //legacy support - the compensation boolean was removed.
  81633. if (arguments.length === 5) {
  81634. _this.webVROptions = arguments[4];
  81635. }
  81636. // default webVR options
  81637. if (_this.webVROptions.trackPosition == undefined) {
  81638. _this.webVROptions.trackPosition = true;
  81639. }
  81640. if (_this.webVROptions.controllerMeshes == undefined) {
  81641. _this.webVROptions.controllerMeshes = true;
  81642. }
  81643. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  81644. _this.webVROptions.defaultLightingOnControllers = true;
  81645. }
  81646. _this.rotationQuaternion = new BABYLON.Quaternion();
  81647. if (_this.webVROptions && _this.webVROptions.positionScale) {
  81648. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  81649. }
  81650. //enable VR
  81651. var engine = _this.getEngine();
  81652. _this._onVREnabled = function (success) { if (success) {
  81653. _this.initControllers();
  81654. } };
  81655. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  81656. engine.initWebVR().add(function (event) {
  81657. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  81658. return;
  81659. }
  81660. _this._vrDevice = event.vrDisplay;
  81661. //reset the rig parameters.
  81662. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  81663. if (_this._attached) {
  81664. _this.getEngine().enableVR();
  81665. }
  81666. });
  81667. if (typeof (VRFrameData) !== "undefined")
  81668. _this._frameData = new VRFrameData();
  81669. /**
  81670. * The idea behind the following lines:
  81671. * objects that have the camera as parent should actually have the rig cameras as a parent.
  81672. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  81673. * the second will not show it correctly.
  81674. *
  81675. * To solve this - each object that has the camera as parent will be added to a protected array.
  81676. * When the rig camera renders, it will take this array and set all of those to be its children.
  81677. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  81678. * Amazing!
  81679. */
  81680. scene.onBeforeCameraRenderObservable.add(function (camera) {
  81681. if (camera.parent === _this && _this.rigParenting) {
  81682. _this._descendants = _this.getDescendants(true, function (n) {
  81683. // don't take the cameras or the controllers!
  81684. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  81685. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  81686. return !isController && !isRigCamera;
  81687. });
  81688. _this._descendants.forEach(function (node) {
  81689. node.parent = camera;
  81690. });
  81691. }
  81692. });
  81693. scene.onAfterCameraRenderObservable.add(function (camera) {
  81694. if (camera.parent === _this && _this.rigParenting) {
  81695. _this._descendants.forEach(function (node) {
  81696. node.parent = _this;
  81697. });
  81698. }
  81699. });
  81700. return _this;
  81701. }
  81702. /**
  81703. * Gets the device distance from the ground in meters.
  81704. * @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.
  81705. */
  81706. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  81707. if (this._standingMatrix) {
  81708. // Add standing matrix offset to get real offset from ground in room
  81709. this._standingMatrix.getTranslationToRef(this._workingVector);
  81710. return this._deviceRoomPosition.y + this._workingVector.y;
  81711. }
  81712. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  81713. return this._defaultHeight || 0;
  81714. };
  81715. /**
  81716. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81717. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  81718. */
  81719. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  81720. var _this = this;
  81721. if (callback === void 0) { callback = function (bool) { }; }
  81722. // Use standing matrix if available
  81723. this.getEngine().initWebVRAsync().then(function (result) {
  81724. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  81725. callback(false);
  81726. }
  81727. else {
  81728. _this._standingMatrix = new BABYLON.Matrix();
  81729. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  81730. if (!_this.getScene().useRightHandedSystem) {
  81731. [2, 6, 8, 9, 14].forEach(function (num) {
  81732. if (_this._standingMatrix) {
  81733. _this._standingMatrix.m[num] *= -1;
  81734. }
  81735. });
  81736. }
  81737. callback(true);
  81738. }
  81739. });
  81740. };
  81741. /**
  81742. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81743. * @returns A promise with a boolean set to if the standing matrix is supported.
  81744. */
  81745. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  81746. var _this = this;
  81747. return new Promise(function (res, rej) {
  81748. _this.useStandingMatrix(function (supported) {
  81749. res(supported);
  81750. });
  81751. });
  81752. };
  81753. /**
  81754. * Disposes the camera
  81755. */
  81756. WebVRFreeCamera.prototype.dispose = function () {
  81757. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  81758. _super.prototype.dispose.call(this);
  81759. };
  81760. /**
  81761. * Gets a vrController by name.
  81762. * @param name The name of the controller to retreive
  81763. * @returns the controller matching the name specified or null if not found
  81764. */
  81765. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  81766. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  81767. var gp = _a[_i];
  81768. if (gp.hand === name) {
  81769. return gp;
  81770. }
  81771. }
  81772. return null;
  81773. };
  81774. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  81775. /**
  81776. * The controller corrisponding to the users left hand.
  81777. */
  81778. get: function () {
  81779. if (!this._leftController) {
  81780. this._leftController = this.getControllerByName("left");
  81781. }
  81782. return this._leftController;
  81783. },
  81784. enumerable: true,
  81785. configurable: true
  81786. });
  81787. ;
  81788. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  81789. /**
  81790. * The controller corrisponding to the users right hand.
  81791. */
  81792. get: function () {
  81793. if (!this._rightController) {
  81794. this._rightController = this.getControllerByName("right");
  81795. }
  81796. return this._rightController;
  81797. },
  81798. enumerable: true,
  81799. configurable: true
  81800. });
  81801. ;
  81802. /**
  81803. * Casts a ray forward from the vrCamera's gaze.
  81804. * @param length Length of the ray (default: 100)
  81805. * @returns the ray corrisponding to the gaze
  81806. */
  81807. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  81808. if (length === void 0) { length = 100; }
  81809. if (this.leftCamera) {
  81810. // Use left eye to avoid computation to compute center on every call
  81811. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  81812. }
  81813. else {
  81814. return _super.prototype.getForwardRay.call(this, length);
  81815. }
  81816. };
  81817. /**
  81818. * Updates the camera based on device's frame data
  81819. */
  81820. WebVRFreeCamera.prototype._checkInputs = function () {
  81821. if (this._vrDevice && this._vrDevice.isPresenting) {
  81822. this._vrDevice.getFrameData(this._frameData);
  81823. this.updateFromDevice(this._frameData.pose);
  81824. }
  81825. _super.prototype._checkInputs.call(this);
  81826. };
  81827. /**
  81828. * Updates the poseControlled values based on the input device pose.
  81829. * @param poseData Pose coming from the device
  81830. */
  81831. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  81832. if (poseData && poseData.orientation) {
  81833. this.rawPose = poseData;
  81834. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  81835. if (this.getScene().useRightHandedSystem) {
  81836. this._deviceRoomRotationQuaternion.z *= -1;
  81837. this._deviceRoomRotationQuaternion.w *= -1;
  81838. }
  81839. if (this.webVROptions.trackPosition && this.rawPose.position) {
  81840. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  81841. if (this.getScene().useRightHandedSystem) {
  81842. this._deviceRoomPosition.z *= -1;
  81843. }
  81844. }
  81845. }
  81846. };
  81847. /**
  81848. * WebVR's attach control will start broadcasting frames to the device.
  81849. * Note that in certain browsers (chrome for example) this function must be called
  81850. * within a user-interaction callback. Example:
  81851. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  81852. *
  81853. * @param element html element to attach the vrDevice to
  81854. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  81855. */
  81856. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  81857. _super.prototype.attachControl.call(this, element, noPreventDefault);
  81858. this._attached = true;
  81859. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  81860. if (this._vrDevice) {
  81861. this.getEngine().enableVR();
  81862. }
  81863. };
  81864. /**
  81865. * Detaches the camera from the html element and disables VR
  81866. *
  81867. * @param element html element to detach from
  81868. */
  81869. WebVRFreeCamera.prototype.detachControl = function (element) {
  81870. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81871. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81872. _super.prototype.detachControl.call(this, element);
  81873. this._attached = false;
  81874. this.getEngine().disableVR();
  81875. };
  81876. /**
  81877. * @returns the name of this class
  81878. */
  81879. WebVRFreeCamera.prototype.getClassName = function () {
  81880. return "WebVRFreeCamera";
  81881. };
  81882. /**
  81883. * Calls resetPose on the vrDisplay
  81884. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  81885. */
  81886. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  81887. //uses the vrDisplay's "resetPose()".
  81888. //pitch and roll won't be affected.
  81889. this._vrDevice.resetPose();
  81890. };
  81891. /**
  81892. * Updates the rig cameras (left and right eye)
  81893. */
  81894. WebVRFreeCamera.prototype._updateRigCameras = function () {
  81895. var camLeft = this._rigCameras[0];
  81896. var camRight = this._rigCameras[1];
  81897. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81898. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81899. camLeft.position.copyFrom(this._deviceRoomPosition);
  81900. camRight.position.copyFrom(this._deviceRoomPosition);
  81901. };
  81902. /**
  81903. * Updates the cached values of the camera
  81904. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  81905. */
  81906. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  81907. var _this = this;
  81908. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  81909. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  81910. if (!this.updateCacheCalled) {
  81911. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  81912. this.updateCacheCalled = true;
  81913. this.update();
  81914. }
  81915. // Set working vector to the device position in room space rotated by the new rotation
  81916. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  81917. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  81918. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  81919. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  81920. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  81921. // Add translation from anchor position
  81922. this._deviceToWorld.getTranslationToRef(this._workingVector);
  81923. this._workingVector.addInPlace(this.position);
  81924. this._workingVector.subtractInPlace(this._cache.position);
  81925. this._deviceToWorld.setTranslation(this._workingVector);
  81926. // Set an inverted matrix to be used when updating the camera
  81927. this._deviceToWorld.invertToRef(this._worldToDevice);
  81928. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  81929. this.controllers.forEach(function (controller) {
  81930. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  81931. controller.update();
  81932. });
  81933. }
  81934. if (!ignoreParentClass) {
  81935. _super.prototype._updateCache.call(this);
  81936. }
  81937. this.updateCacheCalled = false;
  81938. };
  81939. /**
  81940. * Updates the current device position and rotation in the babylon world
  81941. */
  81942. WebVRFreeCamera.prototype.update = function () {
  81943. // Get current device position in babylon world
  81944. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  81945. // Get current device rotation in babylon world
  81946. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  81947. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  81948. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  81949. _super.prototype.update.call(this);
  81950. };
  81951. /**
  81952. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  81953. * @returns an identity matrix
  81954. */
  81955. WebVRFreeCamera.prototype._getViewMatrix = function () {
  81956. return BABYLON.Matrix.Identity();
  81957. };
  81958. /**
  81959. * This function is called by the two RIG cameras.
  81960. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  81961. */
  81962. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  81963. var _this = this;
  81964. // Update the parent camera prior to using a child camera to avoid desynchronization
  81965. var parentCamera = this._cameraRigParams["parentCamera"];
  81966. parentCamera._updateCache();
  81967. //WebVR 1.1
  81968. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  81969. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  81970. if (!this.getScene().useRightHandedSystem) {
  81971. [2, 6, 8, 9, 14].forEach(function (num) {
  81972. _this._webvrViewMatrix.m[num] *= -1;
  81973. });
  81974. }
  81975. // update the camera rotation matrix
  81976. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  81977. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  81978. // Computing target and final matrix
  81979. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  81980. // should the view matrix be updated with scale and position offset?
  81981. if (parentCamera.deviceScaleFactor !== 1) {
  81982. this._webvrViewMatrix.invert();
  81983. // scale the position, if set
  81984. if (parentCamera.deviceScaleFactor) {
  81985. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  81986. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  81987. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  81988. }
  81989. this._webvrViewMatrix.invert();
  81990. }
  81991. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  81992. return this._webvrViewMatrix;
  81993. };
  81994. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  81995. var _this = this;
  81996. var parentCamera = this.parent;
  81997. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  81998. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  81999. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  82000. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  82001. //babylon compatible matrix
  82002. if (!this.getScene().useRightHandedSystem) {
  82003. [8, 9, 10, 11].forEach(function (num) {
  82004. _this._projectionMatrix.m[num] *= -1;
  82005. });
  82006. }
  82007. return this._projectionMatrix;
  82008. };
  82009. /**
  82010. * Initializes the controllers and their meshes
  82011. */
  82012. WebVRFreeCamera.prototype.initControllers = function () {
  82013. var _this = this;
  82014. this.controllers = [];
  82015. var manager = this.getScene().gamepadManager;
  82016. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  82017. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82018. var webVrController = gamepad;
  82019. if (webVrController.defaultModel) {
  82020. webVrController.defaultModel.setEnabled(false);
  82021. }
  82022. if (webVrController.hand === "right") {
  82023. _this._rightController = null;
  82024. }
  82025. if (webVrController.hand === "left") {
  82026. _this._leftController = null;
  82027. }
  82028. var controllerIndex = _this.controllers.indexOf(webVrController);
  82029. if (controllerIndex !== -1) {
  82030. _this.controllers.splice(controllerIndex, 1);
  82031. }
  82032. }
  82033. });
  82034. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  82035. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82036. var webVrController_1 = gamepad;
  82037. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  82038. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  82039. if (_this.webVROptions.controllerMeshes) {
  82040. if (webVrController_1.defaultModel) {
  82041. webVrController_1.defaultModel.setEnabled(true);
  82042. }
  82043. else {
  82044. // Load the meshes
  82045. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  82046. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  82047. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  82048. if (_this.webVROptions.defaultLightingOnControllers) {
  82049. if (!_this._lightOnControllers) {
  82050. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  82051. }
  82052. var activateLightOnSubMeshes_1 = function (mesh, light) {
  82053. var children = mesh.getChildren();
  82054. if (children.length !== 0) {
  82055. children.forEach(function (mesh) {
  82056. light.includedOnlyMeshes.push(mesh);
  82057. activateLightOnSubMeshes_1(mesh, light);
  82058. });
  82059. }
  82060. };
  82061. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  82062. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  82063. }
  82064. });
  82065. }
  82066. }
  82067. webVrController_1.attachToPoseControlledCamera(_this);
  82068. // since this is async - sanity check. Is the controller already stored?
  82069. if (_this.controllers.indexOf(webVrController_1) === -1) {
  82070. //add to the controllers array
  82071. _this.controllers.push(webVrController_1);
  82072. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  82073. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  82074. // So we're overriding setting left & right manually to be sure
  82075. var firstViveWandDetected = false;
  82076. for (var i = 0; i < _this.controllers.length; i++) {
  82077. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82078. if (!firstViveWandDetected) {
  82079. firstViveWandDetected = true;
  82080. _this.controllers[i].hand = "left";
  82081. }
  82082. else {
  82083. _this.controllers[i].hand = "right";
  82084. }
  82085. }
  82086. }
  82087. //did we find enough controllers? Great! let the developer know.
  82088. if (_this.controllers.length >= 2) {
  82089. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  82090. }
  82091. }
  82092. }
  82093. });
  82094. };
  82095. return WebVRFreeCamera;
  82096. }(BABYLON.FreeCamera));
  82097. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  82098. })(BABYLON || (BABYLON = {}));
  82099. //# sourceMappingURL=babylon.webVRCamera.js.map
  82100. "use strict";
  82101. var BABYLON;
  82102. (function (BABYLON) {
  82103. // We're mainly based on the logic defined into the FreeCamera code
  82104. /**
  82105. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  82106. * being tilted forward or back and left or right.
  82107. */
  82108. var DeviceOrientationCamera = /** @class */ (function (_super) {
  82109. __extends(DeviceOrientationCamera, _super);
  82110. /**
  82111. * Creates a new device orientation camera. @see DeviceOrientationCamera
  82112. * @param name The name of the camera
  82113. * @param position The start position camera
  82114. * @param scene The scene the camera belongs to
  82115. */
  82116. function DeviceOrientationCamera(name, position, scene) {
  82117. var _this = _super.call(this, name, position, scene) || this;
  82118. _this._quaternionCache = new BABYLON.Quaternion();
  82119. _this.inputs.addDeviceOrientation();
  82120. return _this;
  82121. }
  82122. /**
  82123. * Gets the current instance class name ("DeviceOrientationCamera").
  82124. * This helps avoiding instanceof at run time.
  82125. * @returns the class name
  82126. */
  82127. DeviceOrientationCamera.prototype.getClassName = function () {
  82128. return "DeviceOrientationCamera";
  82129. };
  82130. /**
  82131. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  82132. */
  82133. DeviceOrientationCamera.prototype._checkInputs = function () {
  82134. _super.prototype._checkInputs.call(this);
  82135. this._quaternionCache.copyFrom(this.rotationQuaternion);
  82136. if (this._initialQuaternion) {
  82137. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82138. }
  82139. };
  82140. /**
  82141. * Reset the camera to its default orientation on the specified axis only.
  82142. * @param axis The axis to reset
  82143. */
  82144. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  82145. var _this = this;
  82146. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  82147. //can only work if this camera has a rotation quaternion already.
  82148. if (!this.rotationQuaternion)
  82149. return;
  82150. if (!this._initialQuaternion) {
  82151. this._initialQuaternion = new BABYLON.Quaternion();
  82152. }
  82153. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  82154. ['x', 'y', 'z'].forEach(function (axisName) {
  82155. if (!axis[axisName]) {
  82156. _this._initialQuaternion[axisName] = 0;
  82157. }
  82158. else {
  82159. _this._initialQuaternion[axisName] *= -1;
  82160. }
  82161. });
  82162. this._initialQuaternion.normalize();
  82163. //force rotation update
  82164. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82165. };
  82166. return DeviceOrientationCamera;
  82167. }(BABYLON.FreeCamera));
  82168. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  82169. })(BABYLON || (BABYLON = {}));
  82170. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  82171. "use strict";
  82172. var BABYLON;
  82173. (function (BABYLON) {
  82174. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  82175. __extends(VRDeviceOrientationFreeCamera, _super);
  82176. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82177. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82178. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82179. var _this = _super.call(this, name, position, scene) || this;
  82180. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82181. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82182. return _this;
  82183. }
  82184. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  82185. return "VRDeviceOrientationFreeCamera";
  82186. };
  82187. return VRDeviceOrientationFreeCamera;
  82188. }(BABYLON.DeviceOrientationCamera));
  82189. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  82190. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  82191. __extends(VRDeviceOrientationGamepadCamera, _super);
  82192. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82193. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82194. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82195. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  82196. _this.inputs.addGamepad();
  82197. return _this;
  82198. }
  82199. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  82200. return "VRDeviceOrientationGamepadCamera";
  82201. };
  82202. return VRDeviceOrientationGamepadCamera;
  82203. }(VRDeviceOrientationFreeCamera));
  82204. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  82205. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  82206. __extends(VRDeviceOrientationArcRotateCamera, _super);
  82207. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  82208. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82209. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82210. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82211. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82212. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82213. _this.inputs.addVRDeviceOrientation();
  82214. return _this;
  82215. }
  82216. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  82217. return "VRDeviceOrientationArcRotateCamera";
  82218. };
  82219. return VRDeviceOrientationArcRotateCamera;
  82220. }(BABYLON.ArcRotateCamera));
  82221. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  82222. })(BABYLON || (BABYLON = {}));
  82223. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  82224. "use strict";
  82225. var BABYLON;
  82226. (function (BABYLON) {
  82227. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  82228. __extends(AnaglyphFreeCamera, _super);
  82229. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  82230. var _this = _super.call(this, name, position, scene) || this;
  82231. _this.interaxialDistance = interaxialDistance;
  82232. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82233. return _this;
  82234. }
  82235. AnaglyphFreeCamera.prototype.getClassName = function () {
  82236. return "AnaglyphFreeCamera";
  82237. };
  82238. return AnaglyphFreeCamera;
  82239. }(BABYLON.FreeCamera));
  82240. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  82241. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  82242. __extends(AnaglyphArcRotateCamera, _super);
  82243. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  82244. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82245. _this.interaxialDistance = interaxialDistance;
  82246. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82247. return _this;
  82248. }
  82249. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  82250. return "AnaglyphArcRotateCamera";
  82251. };
  82252. return AnaglyphArcRotateCamera;
  82253. }(BABYLON.ArcRotateCamera));
  82254. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  82255. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  82256. __extends(AnaglyphGamepadCamera, _super);
  82257. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  82258. var _this = _super.call(this, name, position, scene) || this;
  82259. _this.interaxialDistance = interaxialDistance;
  82260. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82261. return _this;
  82262. }
  82263. AnaglyphGamepadCamera.prototype.getClassName = function () {
  82264. return "AnaglyphGamepadCamera";
  82265. };
  82266. return AnaglyphGamepadCamera;
  82267. }(BABYLON.GamepadCamera));
  82268. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  82269. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  82270. __extends(AnaglyphUniversalCamera, _super);
  82271. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  82272. var _this = _super.call(this, name, position, scene) || this;
  82273. _this.interaxialDistance = interaxialDistance;
  82274. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82275. return _this;
  82276. }
  82277. AnaglyphUniversalCamera.prototype.getClassName = function () {
  82278. return "AnaglyphUniversalCamera";
  82279. };
  82280. return AnaglyphUniversalCamera;
  82281. }(BABYLON.UniversalCamera));
  82282. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  82283. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  82284. __extends(StereoscopicFreeCamera, _super);
  82285. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82286. var _this = _super.call(this, name, position, scene) || this;
  82287. _this.interaxialDistance = interaxialDistance;
  82288. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82289. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82290. return _this;
  82291. }
  82292. StereoscopicFreeCamera.prototype.getClassName = function () {
  82293. return "StereoscopicFreeCamera";
  82294. };
  82295. return StereoscopicFreeCamera;
  82296. }(BABYLON.FreeCamera));
  82297. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  82298. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  82299. __extends(StereoscopicArcRotateCamera, _super);
  82300. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  82301. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82302. _this.interaxialDistance = interaxialDistance;
  82303. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82304. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82305. return _this;
  82306. }
  82307. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  82308. return "StereoscopicArcRotateCamera";
  82309. };
  82310. return StereoscopicArcRotateCamera;
  82311. }(BABYLON.ArcRotateCamera));
  82312. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  82313. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  82314. __extends(StereoscopicGamepadCamera, _super);
  82315. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82316. var _this = _super.call(this, name, position, scene) || this;
  82317. _this.interaxialDistance = interaxialDistance;
  82318. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82319. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82320. return _this;
  82321. }
  82322. StereoscopicGamepadCamera.prototype.getClassName = function () {
  82323. return "StereoscopicGamepadCamera";
  82324. };
  82325. return StereoscopicGamepadCamera;
  82326. }(BABYLON.GamepadCamera));
  82327. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  82328. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  82329. __extends(StereoscopicUniversalCamera, _super);
  82330. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82331. var _this = _super.call(this, name, position, scene) || this;
  82332. _this.interaxialDistance = interaxialDistance;
  82333. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82334. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82335. return _this;
  82336. }
  82337. StereoscopicUniversalCamera.prototype.getClassName = function () {
  82338. return "StereoscopicUniversalCamera";
  82339. };
  82340. return StereoscopicUniversalCamera;
  82341. }(BABYLON.UniversalCamera));
  82342. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  82343. })(BABYLON || (BABYLON = {}));
  82344. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  82345. "use strict";
  82346. var BABYLON;
  82347. (function (BABYLON) {
  82348. var VRExperienceHelperGazer = /** @class */ (function () {
  82349. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  82350. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  82351. this.scene = scene;
  82352. this._pointerDownOnMeshAsked = false;
  82353. this._isActionableMesh = false;
  82354. this._teleportationRequestInitiated = false;
  82355. this._teleportationBackRequestInitiated = false;
  82356. this._dpadPressed = true;
  82357. this._activePointer = false;
  82358. this._id = VRExperienceHelperGazer._idCounter++;
  82359. // Gaze tracker
  82360. if (!gazeTrackerToClone) {
  82361. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  82362. this._gazeTracker.bakeCurrentTransformIntoVertices();
  82363. this._gazeTracker.isPickable = false;
  82364. this._gazeTracker.isVisible = false;
  82365. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  82366. targetMat.specularColor = BABYLON.Color3.Black();
  82367. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82368. targetMat.backFaceCulling = false;
  82369. this._gazeTracker.material = targetMat;
  82370. }
  82371. else {
  82372. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  82373. }
  82374. }
  82375. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  82376. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  82377. };
  82378. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  82379. this._pointerDownOnMeshAsked = true;
  82380. if (this._currentMeshSelected && this._currentHit) {
  82381. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  82382. }
  82383. };
  82384. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  82385. if (this._currentMeshSelected && this._currentHit) {
  82386. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  82387. }
  82388. this._pointerDownOnMeshAsked = false;
  82389. };
  82390. VRExperienceHelperGazer.prototype._activatePointer = function () {
  82391. this._activePointer = true;
  82392. };
  82393. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  82394. this._activePointer = false;
  82395. };
  82396. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  82397. };
  82398. VRExperienceHelperGazer.prototype.dispose = function () {
  82399. this._interactionsEnabled = false;
  82400. this._teleportationEnabled = false;
  82401. };
  82402. VRExperienceHelperGazer._idCounter = 0;
  82403. return VRExperienceHelperGazer;
  82404. }());
  82405. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  82406. __extends(VRExperienceHelperControllerGazer, _super);
  82407. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  82408. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  82409. _this.webVRController = webVRController;
  82410. // Laser pointer
  82411. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  82412. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  82413. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82414. laserPointerMaterial.alpha = 0.6;
  82415. _this._laserPointer.material = laserPointerMaterial;
  82416. _this._laserPointer.rotation.x = Math.PI / 2;
  82417. _this._laserPointer.position.z = -0.5;
  82418. _this._laserPointer.isVisible = false;
  82419. if (!webVRController.mesh) {
  82420. // Create an empty mesh that is used prior to loading the high quality model
  82421. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  82422. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  82423. preloadPointerPose.rotation.x = -0.7;
  82424. preloadMesh.addChild(preloadPointerPose);
  82425. webVRController.attachToMesh(preloadMesh);
  82426. }
  82427. _this._setLaserPointerParent(webVRController.mesh);
  82428. return _this;
  82429. }
  82430. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  82431. return this.webVRController.getForwardRay(length);
  82432. };
  82433. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  82434. _super.prototype._activatePointer.call(this);
  82435. this._laserPointer.isVisible = true;
  82436. };
  82437. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  82438. _super.prototype._deactivatePointer.call(this);
  82439. this._laserPointer.isVisible = false;
  82440. };
  82441. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  82442. this._laserPointer.material.emissiveColor = color;
  82443. };
  82444. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  82445. var makeNotPick = function (root) {
  82446. root.name += " laserPointer";
  82447. root.getChildMeshes().forEach(function (c) {
  82448. makeNotPick(c);
  82449. });
  82450. };
  82451. makeNotPick(mesh);
  82452. var childMeshes = mesh.getChildMeshes();
  82453. this.webVRController._pointingPoseNode = null;
  82454. for (var i = 0; i < childMeshes.length; i++) {
  82455. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  82456. mesh = childMeshes[i];
  82457. this.webVRController._pointingPoseNode = mesh;
  82458. break;
  82459. }
  82460. }
  82461. this._laserPointer.parent = mesh;
  82462. };
  82463. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  82464. this._laserPointer.scaling.y = distance;
  82465. this._laserPointer.position.z = -distance / 2;
  82466. };
  82467. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  82468. _super.prototype.dispose.call(this);
  82469. this._laserPointer.dispose();
  82470. };
  82471. return VRExperienceHelperControllerGazer;
  82472. }(VRExperienceHelperGazer));
  82473. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  82474. __extends(VRExperienceHelperCameraGazer, _super);
  82475. function VRExperienceHelperCameraGazer(getCamera, scene) {
  82476. var _this = _super.call(this, scene) || this;
  82477. _this.getCamera = getCamera;
  82478. return _this;
  82479. }
  82480. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  82481. var camera = this.getCamera();
  82482. if (camera) {
  82483. return camera.getForwardRay(length);
  82484. }
  82485. else {
  82486. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  82487. }
  82488. };
  82489. return VRExperienceHelperCameraGazer;
  82490. }(VRExperienceHelperGazer));
  82491. /**
  82492. * Helps to quickly add VR support to an existing scene.
  82493. * See http://doc.babylonjs.com/how_to/webvr_helper
  82494. */
  82495. var VRExperienceHelper = /** @class */ (function () {
  82496. /**
  82497. * Instantiates a VRExperienceHelper.
  82498. * Helps to quickly add VR support to an existing scene.
  82499. * @param scene The scene the VRExperienceHelper belongs to.
  82500. * @param webVROptions Options to modify the vr experience helper's behavior.
  82501. */
  82502. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  82503. if (webVROptions === void 0) { webVROptions = {}; }
  82504. var _this = this;
  82505. this.webVROptions = webVROptions;
  82506. // Can the system support WebVR, even if a headset isn't plugged in?
  82507. this._webVRsupported = false;
  82508. // If WebVR is supported, is a headset plugged in and are we ready to present?
  82509. this._webVRready = false;
  82510. // Are we waiting for the requestPresent callback to complete?
  82511. this._webVRrequesting = false;
  82512. // Are we presenting to the headset right now?
  82513. this._webVRpresenting = false;
  82514. // Are we presenting in the fullscreen fallback?
  82515. this._fullscreenVRpresenting = false;
  82516. /**
  82517. * Observable raised when entering VR.
  82518. */
  82519. this.onEnteringVRObservable = new BABYLON.Observable();
  82520. /**
  82521. * Observable raised when exiting VR.
  82522. */
  82523. this.onExitingVRObservable = new BABYLON.Observable();
  82524. /**
  82525. * Observable raised when controller mesh is loaded.
  82526. */
  82527. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  82528. this._useCustomVRButton = false;
  82529. this._teleportationRequested = false;
  82530. this._teleportActive = false;
  82531. this._floorMeshesCollection = [];
  82532. this._rotationAllowed = true;
  82533. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  82534. this._rotationRightAsked = false;
  82535. this._rotationLeftAsked = false;
  82536. this._isDefaultTeleportationTarget = true;
  82537. this._teleportationFillColor = "#444444";
  82538. this._teleportationBorderColor = "#FFFFFF";
  82539. this._rotationAngle = 0;
  82540. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  82541. this._padSensibilityUp = 0.65;
  82542. this._padSensibilityDown = 0.35;
  82543. this.leftController = null;
  82544. this.rightController = null;
  82545. /**
  82546. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  82547. */
  82548. this.onNewMeshSelected = new BABYLON.Observable();
  82549. /**
  82550. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  82551. */
  82552. this.onNewMeshPicked = new BABYLON.Observable();
  82553. /**
  82554. * Observable raised before camera teleportation
  82555. */
  82556. this.onBeforeCameraTeleport = new BABYLON.Observable();
  82557. /**
  82558. * Observable raised after camera teleportation
  82559. */
  82560. this.onAfterCameraTeleport = new BABYLON.Observable();
  82561. /**
  82562. * Observable raised when current selected mesh gets unselected
  82563. */
  82564. this.onSelectedMeshUnselected = new BABYLON.Observable();
  82565. /**
  82566. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  82567. */
  82568. this.teleportationEnabled = true;
  82569. this._teleportationInitialized = false;
  82570. this._interactionsEnabled = false;
  82571. this._interactionsRequested = false;
  82572. this._displayGaze = true;
  82573. this._displayLaserPointer = true;
  82574. this._onResize = function () {
  82575. _this.moveButtonToBottomRight();
  82576. if (_this._fullscreenVRpresenting && _this._webVRready) {
  82577. _this.exitVR();
  82578. }
  82579. };
  82580. this._onFullscreenChange = function () {
  82581. if (document.fullscreen !== undefined) {
  82582. _this._fullscreenVRpresenting = document.fullscreen;
  82583. }
  82584. else if (document.mozFullScreen !== undefined) {
  82585. _this._fullscreenVRpresenting = document.mozFullScreen;
  82586. }
  82587. else if (document.webkitIsFullScreen !== undefined) {
  82588. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  82589. }
  82590. else if (document.msIsFullScreen !== undefined) {
  82591. _this._fullscreenVRpresenting = document.msIsFullScreen;
  82592. }
  82593. if (!_this._fullscreenVRpresenting && _this._canvas) {
  82594. _this.exitVR();
  82595. if (!_this._useCustomVRButton) {
  82596. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  82597. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  82598. }
  82599. }
  82600. };
  82601. this.beforeRender = function () {
  82602. if (_this.leftController && _this.leftController._activePointer) {
  82603. _this._castRayAndSelectObject(_this.leftController);
  82604. }
  82605. if (_this.rightController && _this.rightController._activePointer) {
  82606. _this._castRayAndSelectObject(_this.rightController);
  82607. }
  82608. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  82609. _this._castRayAndSelectObject(_this._cameraGazer);
  82610. }
  82611. else {
  82612. _this._cameraGazer._gazeTracker.isVisible = false;
  82613. }
  82614. };
  82615. this._onNewGamepadConnected = function (gamepad) {
  82616. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  82617. if (gamepad.leftStick) {
  82618. gamepad.onleftstickchanged(function (stickValues) {
  82619. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  82620. // Listening to classic/xbox gamepad only if no VR controller is active
  82621. if ((!_this.leftController && !_this.rightController) ||
  82622. ((_this.leftController && !_this.leftController._activePointer) &&
  82623. (_this.rightController && !_this.rightController._activePointer))) {
  82624. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  82625. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  82626. }
  82627. }
  82628. });
  82629. }
  82630. if (gamepad.rightStick) {
  82631. gamepad.onrightstickchanged(function (stickValues) {
  82632. if (_this._teleportationInitialized) {
  82633. _this._checkRotate(stickValues, _this._cameraGazer);
  82634. }
  82635. });
  82636. }
  82637. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  82638. gamepad.onbuttondown(function (buttonPressed) {
  82639. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82640. _this._cameraGazer._selectionPointerDown();
  82641. }
  82642. });
  82643. gamepad.onbuttonup(function (buttonPressed) {
  82644. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82645. _this._cameraGazer._selectionPointerUp();
  82646. }
  82647. });
  82648. }
  82649. }
  82650. else {
  82651. var webVRController = gamepad;
  82652. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  82653. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  82654. _this.rightController = controller;
  82655. }
  82656. else {
  82657. _this.leftController = controller;
  82658. }
  82659. _this._tryEnableInteractionOnController(controller);
  82660. }
  82661. };
  82662. // 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
  82663. this._tryEnableInteractionOnController = function (controller) {
  82664. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  82665. _this._enableInteractionOnController(controller);
  82666. }
  82667. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  82668. _this._enableTeleportationOnController(controller);
  82669. }
  82670. };
  82671. this._onNewGamepadDisconnected = function (gamepad) {
  82672. if (gamepad instanceof BABYLON.WebVRController) {
  82673. if (gamepad.hand === "left" && _this.leftController != null) {
  82674. _this.leftController.dispose();
  82675. _this.leftController = null;
  82676. }
  82677. if (gamepad.hand === "right" && _this.rightController != null) {
  82678. _this.rightController.dispose();
  82679. _this.rightController = null;
  82680. }
  82681. }
  82682. };
  82683. this._workingVector = BABYLON.Vector3.Zero();
  82684. this._workingQuaternion = BABYLON.Quaternion.Identity();
  82685. this._workingMatrix = BABYLON.Matrix.Identity();
  82686. this._scene = scene;
  82687. this._canvas = scene.getEngine().getRenderingCanvas();
  82688. // Parse options
  82689. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  82690. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  82691. }
  82692. if (webVROptions.createDeviceOrientationCamera === undefined) {
  82693. webVROptions.createDeviceOrientationCamera = true;
  82694. }
  82695. if (webVROptions.defaultHeight === undefined) {
  82696. webVROptions.defaultHeight = 1.7;
  82697. }
  82698. if (webVROptions.useCustomVRButton) {
  82699. this._useCustomVRButton = true;
  82700. if (webVROptions.customVRButton) {
  82701. this._btnVR = webVROptions.customVRButton;
  82702. }
  82703. }
  82704. if (webVROptions.rayLength) {
  82705. this._rayLength = webVROptions.rayLength;
  82706. }
  82707. this._defaultHeight = webVROptions.defaultHeight;
  82708. if (webVROptions.positionScale) {
  82709. this._rayLength *= webVROptions.positionScale;
  82710. this._defaultHeight *= webVROptions.positionScale;
  82711. }
  82712. // Set position
  82713. if (this._scene.activeCamera) {
  82714. this._position = this._scene.activeCamera.position.clone();
  82715. }
  82716. else {
  82717. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  82718. }
  82719. // Set non-vr camera
  82720. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  82721. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  82722. // Copy data from existing camera
  82723. if (this._scene.activeCamera) {
  82724. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  82725. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  82726. // Set rotation from previous camera
  82727. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  82728. var targetCamera = this._scene.activeCamera;
  82729. if (targetCamera.rotationQuaternion) {
  82730. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  82731. }
  82732. else {
  82733. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  82734. }
  82735. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  82736. }
  82737. }
  82738. this._scene.activeCamera = this._deviceOrientationCamera;
  82739. if (this._canvas) {
  82740. this._scene.activeCamera.attachControl(this._canvas);
  82741. }
  82742. }
  82743. else {
  82744. this._existingCamera = this._scene.activeCamera;
  82745. }
  82746. // Create VR cameras
  82747. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82748. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  82749. }
  82750. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  82751. this._webVRCamera.useStandingMatrix();
  82752. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  82753. // Create default button
  82754. if (!this._useCustomVRButton) {
  82755. this._btnVR = document.createElement("BUTTON");
  82756. this._btnVR.className = "babylonVRicon";
  82757. this._btnVR.id = "babylonVRiconbtn";
  82758. this._btnVR.title = "Click to switch to VR";
  82759. 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) }";
  82760. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  82761. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  82762. // css += ".babylonVRicon.vrdisplaysupported { }";
  82763. // css += ".babylonVRicon.vrdisplayready { }";
  82764. // css += ".babylonVRicon.vrdisplayrequesting { }";
  82765. var style = document.createElement('style');
  82766. style.appendChild(document.createTextNode(css));
  82767. document.getElementsByTagName('head')[0].appendChild(style);
  82768. this.moveButtonToBottomRight();
  82769. }
  82770. // VR button click event
  82771. if (this._btnVR) {
  82772. this._btnVR.addEventListener("click", function () {
  82773. if (!_this.isInVRMode) {
  82774. _this.enterVR();
  82775. }
  82776. else {
  82777. _this.exitVR();
  82778. }
  82779. });
  82780. }
  82781. // Window events
  82782. window.addEventListener("resize", this._onResize);
  82783. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  82784. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  82785. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  82786. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  82787. // Display vr button when headset is connected
  82788. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82789. this.displayVRButton();
  82790. }
  82791. else {
  82792. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  82793. if (e.vrDisplay) {
  82794. _this.displayVRButton();
  82795. }
  82796. });
  82797. }
  82798. // Exiting VR mode using 'ESC' key on desktop
  82799. this._onKeyDown = function (event) {
  82800. if (event.keyCode === 27 && _this.isInVRMode) {
  82801. _this.exitVR();
  82802. }
  82803. };
  82804. document.addEventListener("keydown", this._onKeyDown);
  82805. // Exiting VR mode double tapping the touch screen
  82806. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  82807. if (_this.isInVRMode) {
  82808. _this.exitVR();
  82809. if (_this._fullscreenVRpresenting) {
  82810. _this._scene.getEngine().switchFullscreen(true);
  82811. }
  82812. }
  82813. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  82814. // Listen for WebVR display changes
  82815. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  82816. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  82817. this._onVRRequestPresentStart = function () {
  82818. _this._webVRrequesting = true;
  82819. _this.updateButtonVisibility();
  82820. };
  82821. this._onVRRequestPresentComplete = function (success) {
  82822. _this._webVRrequesting = false;
  82823. _this.updateButtonVisibility();
  82824. };
  82825. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  82826. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  82827. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  82828. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82829. scene.onDisposeObservable.add(function () {
  82830. _this.dispose();
  82831. });
  82832. // Gamepad connection events
  82833. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  82834. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  82835. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  82836. this.updateButtonVisibility();
  82837. //create easing functions
  82838. this._circleEase = new BABYLON.CircleEase();
  82839. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82840. }
  82841. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  82842. /** Return this.onEnteringVRObservable
  82843. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  82844. */
  82845. get: function () {
  82846. return this.onEnteringVRObservable;
  82847. },
  82848. enumerable: true,
  82849. configurable: true
  82850. });
  82851. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  82852. /** Return this.onExitingVRObservable
  82853. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  82854. */
  82855. get: function () {
  82856. return this.onExitingVRObservable;
  82857. },
  82858. enumerable: true,
  82859. configurable: true
  82860. });
  82861. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  82862. /** Return this.onControllerMeshLoadedObservable
  82863. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  82864. */
  82865. get: function () {
  82866. return this.onControllerMeshLoadedObservable;
  82867. },
  82868. enumerable: true,
  82869. configurable: true
  82870. });
  82871. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  82872. /**
  82873. * The mesh used to display where the user is going to teleport.
  82874. */
  82875. get: function () {
  82876. return this._teleportationTarget;
  82877. },
  82878. /**
  82879. * Sets the mesh to be used to display where the user is going to teleport.
  82880. */
  82881. set: function (value) {
  82882. if (value) {
  82883. value.name = "teleportationTarget";
  82884. this._isDefaultTeleportationTarget = false;
  82885. this._teleportationTarget = value;
  82886. }
  82887. },
  82888. enumerable: true,
  82889. configurable: true
  82890. });
  82891. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  82892. /**
  82893. * The mesh used to display where the user is selecting,
  82894. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  82895. * See http://doc.babylonjs.com/resources/baking_transformations
  82896. */
  82897. get: function () {
  82898. return this._cameraGazer._gazeTracker;
  82899. },
  82900. set: function (value) {
  82901. if (value) {
  82902. this._cameraGazer._gazeTracker = value;
  82903. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  82904. this._cameraGazer._gazeTracker.isPickable = false;
  82905. this._cameraGazer._gazeTracker.isVisible = false;
  82906. this._cameraGazer._gazeTracker.name = "gazeTracker";
  82907. if (this.leftController) {
  82908. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82909. }
  82910. if (this.rightController) {
  82911. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82912. }
  82913. }
  82914. },
  82915. enumerable: true,
  82916. configurable: true
  82917. });
  82918. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  82919. /**
  82920. * If the ray of the gaze should be displayed.
  82921. */
  82922. get: function () {
  82923. return this._displayGaze;
  82924. },
  82925. /**
  82926. * Sets if the ray of the gaze should be displayed.
  82927. */
  82928. set: function (value) {
  82929. this._displayGaze = value;
  82930. if (!value) {
  82931. this._cameraGazer._gazeTracker.isVisible = false;
  82932. if (this.leftController) {
  82933. this.leftController._gazeTracker.isVisible = false;
  82934. }
  82935. if (this.rightController) {
  82936. this.rightController._gazeTracker.isVisible = false;
  82937. }
  82938. }
  82939. },
  82940. enumerable: true,
  82941. configurable: true
  82942. });
  82943. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  82944. /**
  82945. * If the ray of the LaserPointer should be displayed.
  82946. */
  82947. get: function () {
  82948. return this._displayLaserPointer;
  82949. },
  82950. /**
  82951. * Sets if the ray of the LaserPointer should be displayed.
  82952. */
  82953. set: function (value) {
  82954. this._displayLaserPointer = value;
  82955. if (!value) {
  82956. if (this.rightController) {
  82957. this.rightController._deactivatePointer();
  82958. this.rightController._gazeTracker.isVisible = false;
  82959. }
  82960. if (this.leftController) {
  82961. this.leftController._deactivatePointer();
  82962. this.leftController._gazeTracker.isVisible = false;
  82963. }
  82964. }
  82965. else {
  82966. if (this.rightController) {
  82967. this.rightController._activatePointer();
  82968. }
  82969. else if (this.leftController) {
  82970. this.leftController._activatePointer();
  82971. }
  82972. }
  82973. },
  82974. enumerable: true,
  82975. configurable: true
  82976. });
  82977. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  82978. /**
  82979. * The deviceOrientationCamera used as the camera when not in VR.
  82980. */
  82981. get: function () {
  82982. return this._deviceOrientationCamera;
  82983. },
  82984. enumerable: true,
  82985. configurable: true
  82986. });
  82987. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  82988. /**
  82989. * Based on the current WebVR support, returns the current VR camera used.
  82990. */
  82991. get: function () {
  82992. if (this._webVRready) {
  82993. return this._webVRCamera;
  82994. }
  82995. else {
  82996. return this._scene.activeCamera;
  82997. }
  82998. },
  82999. enumerable: true,
  83000. configurable: true
  83001. });
  83002. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  83003. /**
  83004. * The webVRCamera which is used when in VR.
  83005. */
  83006. get: function () {
  83007. return this._webVRCamera;
  83008. },
  83009. enumerable: true,
  83010. configurable: true
  83011. });
  83012. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  83013. /**
  83014. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  83015. */
  83016. get: function () {
  83017. return this._vrDeviceOrientationCamera;
  83018. },
  83019. enumerable: true,
  83020. configurable: true
  83021. });
  83022. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  83023. get: function () {
  83024. var result = this._cameraGazer._teleportationRequestInitiated
  83025. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  83026. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  83027. return result;
  83028. },
  83029. enumerable: true,
  83030. configurable: true
  83031. });
  83032. // Raised when one of the controller has loaded successfully its associated default mesh
  83033. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  83034. if (this.leftController && this.leftController.webVRController == webVRController) {
  83035. if (webVRController.mesh) {
  83036. this.leftController._setLaserPointerParent(webVRController.mesh);
  83037. }
  83038. }
  83039. if (this.rightController && this.rightController.webVRController == webVRController) {
  83040. if (webVRController.mesh) {
  83041. this.rightController._setLaserPointerParent(webVRController.mesh);
  83042. }
  83043. }
  83044. try {
  83045. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  83046. }
  83047. catch (err) {
  83048. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  83049. }
  83050. };
  83051. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  83052. /**
  83053. * Gets a value indicating if we are currently in VR mode.
  83054. */
  83055. get: function () {
  83056. return this._webVRpresenting || this._fullscreenVRpresenting;
  83057. },
  83058. enumerable: true,
  83059. configurable: true
  83060. });
  83061. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  83062. var vrDisplay = this._scene.getEngine().getVRDevice();
  83063. if (vrDisplay) {
  83064. var wasPresenting = this._webVRpresenting;
  83065. // A VR display is connected
  83066. this._webVRpresenting = vrDisplay.isPresenting;
  83067. if (wasPresenting && !this._webVRpresenting)
  83068. this.exitVR();
  83069. }
  83070. else {
  83071. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  83072. }
  83073. this.updateButtonVisibility();
  83074. };
  83075. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  83076. this._webVRsupported = eventArgs.vrSupported;
  83077. this._webVRready = !!eventArgs.vrDisplay;
  83078. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  83079. this.updateButtonVisibility();
  83080. };
  83081. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  83082. if (this._canvas && !this._useCustomVRButton) {
  83083. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  83084. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  83085. }
  83086. };
  83087. VRExperienceHelper.prototype.displayVRButton = function () {
  83088. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  83089. document.body.appendChild(this._btnVR);
  83090. this._btnVRDisplayed = true;
  83091. }
  83092. };
  83093. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  83094. if (!this._btnVR || this._useCustomVRButton) {
  83095. return;
  83096. }
  83097. this._btnVR.className = "babylonVRicon";
  83098. if (this.isInVRMode) {
  83099. this._btnVR.className += " vrdisplaypresenting";
  83100. }
  83101. else {
  83102. if (this._webVRready)
  83103. this._btnVR.className += " vrdisplayready";
  83104. if (this._webVRsupported)
  83105. this._btnVR.className += " vrdisplaysupported";
  83106. if (this._webVRrequesting)
  83107. this._btnVR.className += " vrdisplayrequesting";
  83108. }
  83109. };
  83110. /**
  83111. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  83112. * Otherwise, will use the fullscreen API.
  83113. */
  83114. VRExperienceHelper.prototype.enterVR = function () {
  83115. if (this.onEnteringVRObservable) {
  83116. try {
  83117. this.onEnteringVRObservable.notifyObservers(this);
  83118. }
  83119. catch (err) {
  83120. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  83121. }
  83122. }
  83123. if (this._scene.activeCamera) {
  83124. this._position = this._scene.activeCamera.position.clone();
  83125. // make sure that we return to the last active camera
  83126. this._existingCamera = this._scene.activeCamera;
  83127. }
  83128. if (this._webVRrequesting)
  83129. return;
  83130. // If WebVR is supported and a headset is connected
  83131. if (this._webVRready) {
  83132. if (!this._webVRpresenting) {
  83133. this._webVRCamera.position = this._position;
  83134. this._scene.activeCamera = this._webVRCamera;
  83135. }
  83136. }
  83137. else if (this._vrDeviceOrientationCamera) {
  83138. this._vrDeviceOrientationCamera.position = this._position;
  83139. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  83140. this._scene.getEngine().switchFullscreen(true);
  83141. this.updateButtonVisibility();
  83142. }
  83143. if (this._scene.activeCamera && this._canvas) {
  83144. this._scene.activeCamera.attachControl(this._canvas);
  83145. }
  83146. if (this._interactionsEnabled) {
  83147. this._scene.registerBeforeRender(this.beforeRender);
  83148. }
  83149. };
  83150. /**
  83151. * Attempt to exit VR, or fullscreen.
  83152. */
  83153. VRExperienceHelper.prototype.exitVR = function () {
  83154. if (this.onExitingVRObservable) {
  83155. try {
  83156. this.onExitingVRObservable.notifyObservers(this);
  83157. }
  83158. catch (err) {
  83159. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  83160. }
  83161. }
  83162. if (this._webVRpresenting) {
  83163. this._scene.getEngine().disableVR();
  83164. }
  83165. if (this._scene.activeCamera) {
  83166. this._position = this._scene.activeCamera.position.clone();
  83167. }
  83168. if (this._deviceOrientationCamera) {
  83169. this._deviceOrientationCamera.position = this._position;
  83170. this._scene.activeCamera = this._deviceOrientationCamera;
  83171. if (this._canvas) {
  83172. this._scene.activeCamera.attachControl(this._canvas);
  83173. }
  83174. }
  83175. else if (this._existingCamera) {
  83176. this._existingCamera.position = this._position;
  83177. this._scene.activeCamera = this._existingCamera;
  83178. }
  83179. this.updateButtonVisibility();
  83180. if (this._interactionsEnabled) {
  83181. this._scene.unregisterBeforeRender(this.beforeRender);
  83182. }
  83183. };
  83184. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  83185. /**
  83186. * The position of the vr experience helper.
  83187. */
  83188. get: function () {
  83189. return this._position;
  83190. },
  83191. /**
  83192. * Sets the position of the vr experience helper.
  83193. */
  83194. set: function (value) {
  83195. this._position = value;
  83196. if (this._scene.activeCamera) {
  83197. this._scene.activeCamera.position = value;
  83198. }
  83199. },
  83200. enumerable: true,
  83201. configurable: true
  83202. });
  83203. /**
  83204. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  83205. */
  83206. VRExperienceHelper.prototype.enableInteractions = function () {
  83207. var _this = this;
  83208. if (!this._interactionsEnabled) {
  83209. this._interactionsRequested = true;
  83210. if (this.leftController) {
  83211. this._enableInteractionOnController(this.leftController);
  83212. }
  83213. if (this.rightController) {
  83214. this._enableInteractionOnController(this.rightController);
  83215. }
  83216. this.raySelectionPredicate = function (mesh) {
  83217. return mesh.isVisible;
  83218. };
  83219. this.meshSelectionPredicate = function (mesh) {
  83220. return true;
  83221. };
  83222. this._raySelectionPredicate = function (mesh) {
  83223. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  83224. && mesh.name.indexOf("teleportationTarget") === -1
  83225. && mesh.name.indexOf("torusTeleportation") === -1
  83226. && mesh.name.indexOf("laserPointer") === -1)) {
  83227. return _this.raySelectionPredicate(mesh);
  83228. }
  83229. return false;
  83230. };
  83231. this._interactionsEnabled = true;
  83232. }
  83233. };
  83234. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  83235. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  83236. if (this._floorMeshesCollection[i].id === mesh.id) {
  83237. return true;
  83238. }
  83239. }
  83240. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  83241. return true;
  83242. }
  83243. return false;
  83244. };
  83245. /**
  83246. * Adds a floor mesh to be used for teleportation.
  83247. * @param floorMesh the mesh to be used for teleportation.
  83248. */
  83249. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  83250. if (!this._floorMeshesCollection) {
  83251. return;
  83252. }
  83253. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  83254. return;
  83255. }
  83256. this._floorMeshesCollection.push(floorMesh);
  83257. };
  83258. /**
  83259. * Removes a floor mesh from being used for teleportation.
  83260. * @param floorMesh the mesh to be removed.
  83261. */
  83262. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  83263. if (!this._floorMeshesCollection) {
  83264. return;
  83265. }
  83266. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  83267. if (meshIndex !== -1) {
  83268. this._floorMeshesCollection.splice(meshIndex, 1);
  83269. }
  83270. };
  83271. /**
  83272. * Enables interactions and teleportation using the VR controllers and gaze.
  83273. * @param vrTeleportationOptions options to modify teleportation behavior.
  83274. */
  83275. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  83276. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  83277. if (!this._teleportationInitialized) {
  83278. this._teleportationRequested = true;
  83279. this.enableInteractions();
  83280. if (vrTeleportationOptions.floorMeshName) {
  83281. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  83282. }
  83283. if (vrTeleportationOptions.floorMeshes) {
  83284. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  83285. }
  83286. if (this.leftController != null) {
  83287. this._enableTeleportationOnController(this.leftController);
  83288. }
  83289. if (this.rightController != null) {
  83290. this._enableTeleportationOnController(this.rightController);
  83291. }
  83292. // Creates an image processing post process for the vignette not relying
  83293. // on the main scene configuration for image processing to reduce setup and spaces
  83294. // (gamma/linear) conflicts.
  83295. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  83296. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  83297. imageProcessingConfiguration.vignetteEnabled = true;
  83298. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  83299. this._webVRCamera.detachPostProcess(this._postProcessMove);
  83300. this._teleportationInitialized = true;
  83301. if (this._isDefaultTeleportationTarget) {
  83302. this._createTeleportationCircles();
  83303. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  83304. }
  83305. }
  83306. };
  83307. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  83308. var _this = this;
  83309. var controllerMesh = controller.webVRController.mesh;
  83310. if (controllerMesh) {
  83311. controller._interactionsEnabled = true;
  83312. controller._activatePointer();
  83313. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  83314. // Enabling / disabling laserPointer
  83315. if (_this._displayLaserPointer && stateObject.value === 1) {
  83316. if (controller._activePointer) {
  83317. controller._deactivatePointer();
  83318. }
  83319. else {
  83320. controller._activatePointer();
  83321. }
  83322. if (_this.displayGaze) {
  83323. controller._gazeTracker.isVisible = controller._activePointer;
  83324. }
  83325. }
  83326. });
  83327. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  83328. if (!controller._pointerDownOnMeshAsked) {
  83329. if (stateObject.value > _this._padSensibilityUp) {
  83330. controller._selectionPointerDown();
  83331. }
  83332. }
  83333. else if (stateObject.value < _this._padSensibilityDown) {
  83334. controller._selectionPointerUp();
  83335. }
  83336. });
  83337. }
  83338. };
  83339. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  83340. // Dont teleport if another gaze already requested teleportation
  83341. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  83342. return;
  83343. }
  83344. if (!gazer._teleportationRequestInitiated) {
  83345. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  83346. gazer._activatePointer();
  83347. gazer._teleportationRequestInitiated = true;
  83348. }
  83349. }
  83350. else {
  83351. // Listening to the proper controller values changes to confirm teleportation
  83352. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  83353. if (this._teleportActive) {
  83354. this._teleportCamera(this._haloCenter);
  83355. }
  83356. gazer._teleportationRequestInitiated = false;
  83357. }
  83358. }
  83359. };
  83360. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  83361. // Only rotate when user is not currently selecting a teleportation location
  83362. if (gazer._teleportationRequestInitiated) {
  83363. return;
  83364. }
  83365. if (!this._rotationLeftAsked) {
  83366. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  83367. this._rotationLeftAsked = true;
  83368. if (this._rotationAllowed) {
  83369. this._rotateCamera(false);
  83370. }
  83371. }
  83372. }
  83373. else {
  83374. if (stateObject.x > -this._padSensibilityDown) {
  83375. this._rotationLeftAsked = false;
  83376. }
  83377. }
  83378. if (!this._rotationRightAsked) {
  83379. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  83380. this._rotationRightAsked = true;
  83381. if (this._rotationAllowed) {
  83382. this._rotateCamera(true);
  83383. }
  83384. }
  83385. }
  83386. else {
  83387. if (stateObject.x < this._padSensibilityDown) {
  83388. this._rotationRightAsked = false;
  83389. }
  83390. }
  83391. };
  83392. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  83393. // Only teleport backwards when user is not currently selecting a teleportation location
  83394. if (gazer._teleportationRequestInitiated) {
  83395. return;
  83396. }
  83397. // Teleport backwards
  83398. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  83399. if (!gazer._teleportationBackRequestInitiated) {
  83400. if (!this.currentVRCamera) {
  83401. return;
  83402. }
  83403. // Get rotation and position of the current camera
  83404. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  83405. var position = this.currentVRCamera.position;
  83406. // If the camera has device position, use that instead
  83407. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  83408. rotation = this.currentVRCamera.deviceRotationQuaternion;
  83409. position = this.currentVRCamera.devicePosition;
  83410. }
  83411. // Get matrix with only the y rotation of the device rotation
  83412. rotation.toEulerAnglesToRef(this._workingVector);
  83413. this._workingVector.z = 0;
  83414. this._workingVector.x = 0;
  83415. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  83416. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  83417. // Rotate backwards ray by device rotation to cast at the ground behind the user
  83418. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  83419. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  83420. var ray = new BABYLON.Ray(position, this._workingVector);
  83421. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  83422. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  83423. this._teleportCamera(hit.pickedPoint);
  83424. }
  83425. gazer._teleportationBackRequestInitiated = true;
  83426. }
  83427. }
  83428. else {
  83429. gazer._teleportationBackRequestInitiated = false;
  83430. }
  83431. };
  83432. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  83433. var _this = this;
  83434. var controllerMesh = controller.webVRController.mesh;
  83435. if (controllerMesh) {
  83436. if (!controller._interactionsEnabled) {
  83437. this._enableInteractionOnController(controller);
  83438. }
  83439. controller._interactionsEnabled = true;
  83440. controller._teleportationEnabled = true;
  83441. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  83442. controller._dpadPressed = false;
  83443. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  83444. controller._dpadPressed = stateObject.pressed;
  83445. if (!controller._dpadPressed) {
  83446. _this._rotationLeftAsked = false;
  83447. _this._rotationRightAsked = false;
  83448. controller._teleportationBackRequestInitiated = false;
  83449. }
  83450. });
  83451. }
  83452. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  83453. if (_this.teleportationEnabled) {
  83454. _this._checkTeleportBackwards(stateObject, controller);
  83455. _this._checkTeleportWithRay(stateObject, controller);
  83456. }
  83457. _this._checkRotate(stateObject, controller);
  83458. });
  83459. }
  83460. };
  83461. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  83462. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  83463. this._teleportationTarget.isPickable = false;
  83464. var length = 512;
  83465. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  83466. dynamicTexture.hasAlpha = true;
  83467. var context = dynamicTexture.getContext();
  83468. var centerX = length / 2;
  83469. var centerY = length / 2;
  83470. var radius = 200;
  83471. context.beginPath();
  83472. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  83473. context.fillStyle = this._teleportationFillColor;
  83474. context.fill();
  83475. context.lineWidth = 10;
  83476. context.strokeStyle = this._teleportationBorderColor;
  83477. context.stroke();
  83478. context.closePath();
  83479. dynamicTexture.update();
  83480. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  83481. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  83482. this._teleportationTarget.material = teleportationCircleMaterial;
  83483. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  83484. torus.isPickable = false;
  83485. torus.parent = this._teleportationTarget;
  83486. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  83487. var keys = [];
  83488. keys.push({
  83489. frame: 0,
  83490. value: 0
  83491. });
  83492. keys.push({
  83493. frame: 30,
  83494. value: 0.4
  83495. });
  83496. keys.push({
  83497. frame: 60,
  83498. value: 0
  83499. });
  83500. animationInnerCircle.setKeys(keys);
  83501. var easingFunction = new BABYLON.SineEase();
  83502. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83503. animationInnerCircle.setEasingFunction(easingFunction);
  83504. torus.animations = [];
  83505. torus.animations.push(animationInnerCircle);
  83506. this._scene.beginAnimation(torus, 0, 60, true);
  83507. this._hideTeleportationTarget();
  83508. };
  83509. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  83510. this._teleportActive = true;
  83511. if (this._teleportationInitialized) {
  83512. this._teleportationTarget.isVisible = true;
  83513. if (this._isDefaultTeleportationTarget) {
  83514. this._teleportationTarget.getChildren()[0].isVisible = true;
  83515. }
  83516. }
  83517. };
  83518. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  83519. this._teleportActive = false;
  83520. if (this._teleportationInitialized) {
  83521. this._teleportationTarget.isVisible = false;
  83522. if (this._isDefaultTeleportationTarget) {
  83523. this._teleportationTarget.getChildren()[0].isVisible = false;
  83524. }
  83525. }
  83526. };
  83527. VRExperienceHelper.prototype._rotateCamera = function (right) {
  83528. var _this = this;
  83529. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83530. return;
  83531. }
  83532. if (right) {
  83533. this._rotationAngle++;
  83534. }
  83535. else {
  83536. this._rotationAngle--;
  83537. }
  83538. this.currentVRCamera.animations = [];
  83539. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  83540. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83541. var animationRotationKeys = [];
  83542. animationRotationKeys.push({
  83543. frame: 0,
  83544. value: this.currentVRCamera.rotationQuaternion
  83545. });
  83546. animationRotationKeys.push({
  83547. frame: 6,
  83548. value: target
  83549. });
  83550. animationRotation.setKeys(animationRotationKeys);
  83551. animationRotation.setEasingFunction(this._circleEase);
  83552. this.currentVRCamera.animations.push(animationRotation);
  83553. this._postProcessMove.animations = [];
  83554. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83555. var vignetteWeightKeys = [];
  83556. vignetteWeightKeys.push({
  83557. frame: 0,
  83558. value: 0
  83559. });
  83560. vignetteWeightKeys.push({
  83561. frame: 3,
  83562. value: 4
  83563. });
  83564. vignetteWeightKeys.push({
  83565. frame: 6,
  83566. value: 0
  83567. });
  83568. animationPP.setKeys(vignetteWeightKeys);
  83569. animationPP.setEasingFunction(this._circleEase);
  83570. this._postProcessMove.animations.push(animationPP);
  83571. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83572. var vignetteStretchKeys = [];
  83573. vignetteStretchKeys.push({
  83574. frame: 0,
  83575. value: 0
  83576. });
  83577. vignetteStretchKeys.push({
  83578. frame: 3,
  83579. value: 10
  83580. });
  83581. vignetteStretchKeys.push({
  83582. frame: 6,
  83583. value: 0
  83584. });
  83585. animationPP2.setKeys(vignetteStretchKeys);
  83586. animationPP2.setEasingFunction(this._circleEase);
  83587. this._postProcessMove.animations.push(animationPP2);
  83588. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83589. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83590. this._postProcessMove.samples = 4;
  83591. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83592. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  83593. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83594. });
  83595. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  83596. };
  83597. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  83598. if (hit.pickedPoint) {
  83599. if (gazer._teleportationRequestInitiated) {
  83600. this._displayTeleportationTarget();
  83601. this._haloCenter.copyFrom(hit.pickedPoint);
  83602. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  83603. }
  83604. var pickNormal = hit.getNormal(true, false);
  83605. if (pickNormal) {
  83606. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83607. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83608. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  83609. }
  83610. this._teleportationTarget.position.y += 0.1;
  83611. }
  83612. };
  83613. VRExperienceHelper.prototype._teleportCamera = function (location) {
  83614. var _this = this;
  83615. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83616. return;
  83617. }
  83618. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  83619. // offset of the headset from the anchor.
  83620. if (this.webVRCamera.leftCamera) {
  83621. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  83622. this._workingVector.subtractInPlace(this.webVRCamera.position);
  83623. location.subtractToRef(this._workingVector, this._workingVector);
  83624. }
  83625. else {
  83626. this._workingVector.copyFrom(location);
  83627. }
  83628. // Add height to account for user's height offset
  83629. if (this.isInVRMode) {
  83630. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  83631. }
  83632. else {
  83633. this._workingVector.y += this._defaultHeight;
  83634. }
  83635. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  83636. // Create animation from the camera's position to the new location
  83637. this.currentVRCamera.animations = [];
  83638. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83639. var animationCameraTeleportationKeys = [{
  83640. frame: 0,
  83641. value: this.currentVRCamera.position
  83642. },
  83643. {
  83644. frame: 11,
  83645. value: this._workingVector
  83646. }
  83647. ];
  83648. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  83649. animationCameraTeleportation.setEasingFunction(this._circleEase);
  83650. this.currentVRCamera.animations.push(animationCameraTeleportation);
  83651. this._postProcessMove.animations = [];
  83652. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83653. var vignetteWeightKeys = [];
  83654. vignetteWeightKeys.push({
  83655. frame: 0,
  83656. value: 0
  83657. });
  83658. vignetteWeightKeys.push({
  83659. frame: 5,
  83660. value: 8
  83661. });
  83662. vignetteWeightKeys.push({
  83663. frame: 11,
  83664. value: 0
  83665. });
  83666. animationPP.setKeys(vignetteWeightKeys);
  83667. this._postProcessMove.animations.push(animationPP);
  83668. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83669. var vignetteStretchKeys = [];
  83670. vignetteStretchKeys.push({
  83671. frame: 0,
  83672. value: 0
  83673. });
  83674. vignetteStretchKeys.push({
  83675. frame: 5,
  83676. value: 10
  83677. });
  83678. vignetteStretchKeys.push({
  83679. frame: 11,
  83680. value: 0
  83681. });
  83682. animationPP2.setKeys(vignetteStretchKeys);
  83683. this._postProcessMove.animations.push(animationPP2);
  83684. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83685. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83686. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83687. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  83688. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83689. });
  83690. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  83691. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  83692. });
  83693. this._hideTeleportationTarget();
  83694. };
  83695. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  83696. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83697. return;
  83698. }
  83699. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  83700. // Moving the gazeTracker on the mesh face targetted
  83701. if (hit && hit.pickedPoint) {
  83702. if (this._displayGaze) {
  83703. var multiplier = 1;
  83704. gazer._gazeTracker.isVisible = true;
  83705. if (gazer._isActionableMesh) {
  83706. multiplier = 3;
  83707. }
  83708. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  83709. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  83710. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  83711. var pickNormal = hit.getNormal();
  83712. // To avoid z-fighting
  83713. var deltaFighting = 0.002;
  83714. if (pickNormal) {
  83715. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83716. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83717. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  83718. }
  83719. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  83720. if (gazer._gazeTracker.position.x < 0) {
  83721. gazer._gazeTracker.position.x += deltaFighting;
  83722. }
  83723. else {
  83724. gazer._gazeTracker.position.x -= deltaFighting;
  83725. }
  83726. if (gazer._gazeTracker.position.y < 0) {
  83727. gazer._gazeTracker.position.y += deltaFighting;
  83728. }
  83729. else {
  83730. gazer._gazeTracker.position.y -= deltaFighting;
  83731. }
  83732. if (gazer._gazeTracker.position.z < 0) {
  83733. gazer._gazeTracker.position.z += deltaFighting;
  83734. }
  83735. else {
  83736. gazer._gazeTracker.position.z -= deltaFighting;
  83737. }
  83738. }
  83739. // Changing the size of the laser pointer based on the distance from the targetted point
  83740. gazer._updatePointerDistance(hit.distance);
  83741. }
  83742. else {
  83743. gazer._gazeTracker.isVisible = false;
  83744. }
  83745. if (hit && hit.pickedMesh) {
  83746. gazer._currentHit = hit;
  83747. if (gazer._pointerDownOnMeshAsked) {
  83748. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  83749. }
  83750. // The object selected is the floor, we're in a teleportation scenario
  83751. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  83752. // Moving the teleportation area to this targetted point
  83753. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  83754. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  83755. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83756. }
  83757. gazer._currentMeshSelected = null;
  83758. if (gazer._teleportationRequestInitiated) {
  83759. this._moveTeleportationSelectorTo(hit, gazer);
  83760. }
  83761. return;
  83762. }
  83763. // If not, we're in a selection scenario
  83764. //this._teleportationAllowed = false;
  83765. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  83766. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  83767. this.onNewMeshPicked.notifyObservers(hit);
  83768. gazer._currentMeshSelected = hit.pickedMesh;
  83769. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  83770. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  83771. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  83772. gazer._isActionableMesh = true;
  83773. }
  83774. else {
  83775. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83776. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83777. gazer._isActionableMesh = false;
  83778. }
  83779. try {
  83780. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  83781. }
  83782. catch (err) {
  83783. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  83784. }
  83785. }
  83786. else {
  83787. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83788. gazer._currentMeshSelected = null;
  83789. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83790. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83791. }
  83792. }
  83793. }
  83794. else {
  83795. gazer._currentHit = null;
  83796. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83797. gazer._currentMeshSelected = null;
  83798. //this._teleportationAllowed = false;
  83799. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83800. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83801. }
  83802. };
  83803. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  83804. if (mesh) {
  83805. this.onSelectedMeshUnselected.notifyObservers(mesh);
  83806. }
  83807. };
  83808. /**
  83809. * Sets the color of the laser ray from the vr controllers.
  83810. * @param color new color for the ray.
  83811. */
  83812. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  83813. if (this.leftController) {
  83814. this.leftController._setLaserPointerColor(color);
  83815. }
  83816. if (this.rightController) {
  83817. this.rightController._setLaserPointerColor(color);
  83818. }
  83819. };
  83820. /**
  83821. * Sets the color of the ray from the vr headsets gaze.
  83822. * @param color new color for the ray.
  83823. */
  83824. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  83825. if (!this._cameraGazer._gazeTracker.material) {
  83826. return;
  83827. }
  83828. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  83829. if (this.leftController) {
  83830. this.leftController._gazeTracker.material.emissiveColor = color;
  83831. }
  83832. if (this.rightController) {
  83833. this.rightController._gazeTracker.material.emissiveColor = color;
  83834. }
  83835. };
  83836. /**
  83837. * Exits VR and disposes of the vr experience helper
  83838. */
  83839. VRExperienceHelper.prototype.dispose = function () {
  83840. if (this.isInVRMode) {
  83841. this.exitVR();
  83842. }
  83843. if (this._postProcessMove) {
  83844. this._postProcessMove.dispose();
  83845. }
  83846. if (this._webVRCamera) {
  83847. this._webVRCamera.dispose();
  83848. }
  83849. if (this._vrDeviceOrientationCamera) {
  83850. this._vrDeviceOrientationCamera.dispose();
  83851. }
  83852. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  83853. document.body.removeChild(this._btnVR);
  83854. }
  83855. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  83856. this._deviceOrientationCamera.dispose();
  83857. }
  83858. if (this._cameraGazer) {
  83859. this._cameraGazer.dispose();
  83860. }
  83861. if (this.leftController) {
  83862. this.leftController.dispose();
  83863. }
  83864. if (this.rightController) {
  83865. this.rightController.dispose();
  83866. }
  83867. if (this._teleportationTarget) {
  83868. this._teleportationTarget.dispose();
  83869. }
  83870. this._floorMeshesCollection = [];
  83871. document.removeEventListener("keydown", this._onKeyDown);
  83872. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83873. window.removeEventListener("resize", this._onResize);
  83874. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  83875. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  83876. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  83877. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  83878. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  83879. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  83880. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  83881. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83882. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  83883. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  83884. this._scene.unregisterBeforeRender(this.beforeRender);
  83885. };
  83886. /**
  83887. * Gets the name of the VRExperienceHelper class
  83888. * @returns "VRExperienceHelper"
  83889. */
  83890. VRExperienceHelper.prototype.getClassName = function () {
  83891. return "VRExperienceHelper";
  83892. };
  83893. return VRExperienceHelper;
  83894. }());
  83895. BABYLON.VRExperienceHelper = VRExperienceHelper;
  83896. })(BABYLON || (BABYLON = {}));
  83897. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  83898. "use strict";
  83899. // Mainly based on these 2 articles :
  83900. // 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
  83901. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  83902. var BABYLON;
  83903. (function (BABYLON) {
  83904. var JoystickAxis;
  83905. (function (JoystickAxis) {
  83906. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  83907. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  83908. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  83909. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  83910. var VirtualJoystick = /** @class */ (function () {
  83911. function VirtualJoystick(leftJoystick) {
  83912. var _this = this;
  83913. if (leftJoystick) {
  83914. this._leftJoystick = true;
  83915. }
  83916. else {
  83917. this._leftJoystick = false;
  83918. }
  83919. VirtualJoystick._globalJoystickIndex++;
  83920. // By default left & right arrow keys are moving the X
  83921. // and up & down keys are moving the Y
  83922. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83923. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83924. this.reverseLeftRight = false;
  83925. this.reverseUpDown = false;
  83926. // collections of pointers
  83927. this._touches = new BABYLON.StringDictionary();
  83928. this.deltaPosition = BABYLON.Vector3.Zero();
  83929. this._joystickSensibility = 25;
  83930. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83931. this._onResize = function (evt) {
  83932. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83933. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83934. if (VirtualJoystick.vjCanvas) {
  83935. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  83936. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  83937. }
  83938. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  83939. };
  83940. // injecting a canvas element on top of the canvas 3D game
  83941. if (!VirtualJoystick.vjCanvas) {
  83942. window.addEventListener("resize", this._onResize, false);
  83943. VirtualJoystick.vjCanvas = document.createElement("canvas");
  83944. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83945. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83946. VirtualJoystick.vjCanvas.width = window.innerWidth;
  83947. VirtualJoystick.vjCanvas.height = window.innerHeight;
  83948. VirtualJoystick.vjCanvas.style.width = "100%";
  83949. VirtualJoystick.vjCanvas.style.height = "100%";
  83950. VirtualJoystick.vjCanvas.style.position = "absolute";
  83951. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  83952. VirtualJoystick.vjCanvas.style.top = "0px";
  83953. VirtualJoystick.vjCanvas.style.left = "0px";
  83954. VirtualJoystick.vjCanvas.style.zIndex = "5";
  83955. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  83956. // Support for jQuery PEP polyfill
  83957. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  83958. var context = VirtualJoystick.vjCanvas.getContext('2d');
  83959. if (!context) {
  83960. throw new Error("Unable to create canvas for virtual joystick");
  83961. }
  83962. VirtualJoystick.vjCanvasContext = context;
  83963. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  83964. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83965. document.body.appendChild(VirtualJoystick.vjCanvas);
  83966. }
  83967. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  83968. this.pressed = false;
  83969. // default joystick color
  83970. this._joystickColor = "cyan";
  83971. this._joystickPointerID = -1;
  83972. // current joystick position
  83973. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  83974. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  83975. // origin joystick position
  83976. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  83977. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  83978. this._onPointerDownHandlerRef = function (evt) {
  83979. _this._onPointerDown(evt);
  83980. };
  83981. this._onPointerMoveHandlerRef = function (evt) {
  83982. _this._onPointerMove(evt);
  83983. };
  83984. this._onPointerUpHandlerRef = function (evt) {
  83985. _this._onPointerUp(evt);
  83986. };
  83987. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  83988. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  83989. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  83990. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  83991. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  83992. evt.preventDefault(); // Disables system menu
  83993. }, false);
  83994. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  83995. }
  83996. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  83997. this._joystickSensibility = newJoystickSensibility;
  83998. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83999. };
  84000. VirtualJoystick.prototype._onPointerDown = function (e) {
  84001. var positionOnScreenCondition;
  84002. e.preventDefault();
  84003. if (this._leftJoystick === true) {
  84004. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  84005. }
  84006. else {
  84007. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  84008. }
  84009. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  84010. // First contact will be dedicated to the virtual joystick
  84011. this._joystickPointerID = e.pointerId;
  84012. this._joystickPointerStartPos.x = e.clientX;
  84013. this._joystickPointerStartPos.y = e.clientY;
  84014. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  84015. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  84016. this._deltaJoystickVector.x = 0;
  84017. this._deltaJoystickVector.y = 0;
  84018. this.pressed = true;
  84019. this._touches.add(e.pointerId.toString(), e);
  84020. }
  84021. else {
  84022. // You can only trigger the action buttons with a joystick declared
  84023. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  84024. this._action();
  84025. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  84026. }
  84027. }
  84028. };
  84029. VirtualJoystick.prototype._onPointerMove = function (e) {
  84030. // If the current pointer is the one associated to the joystick (first touch contact)
  84031. if (this._joystickPointerID == e.pointerId) {
  84032. this._joystickPointerPos.x = e.clientX;
  84033. this._joystickPointerPos.y = e.clientY;
  84034. this._deltaJoystickVector = this._joystickPointerPos.clone();
  84035. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  84036. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  84037. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  84038. switch (this._axisTargetedByLeftAndRight) {
  84039. case JoystickAxis.X:
  84040. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  84041. break;
  84042. case JoystickAxis.Y:
  84043. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  84044. break;
  84045. case JoystickAxis.Z:
  84046. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  84047. break;
  84048. }
  84049. var directionUpDown = this.reverseUpDown ? 1 : -1;
  84050. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  84051. switch (this._axisTargetedByUpAndDown) {
  84052. case JoystickAxis.X:
  84053. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  84054. break;
  84055. case JoystickAxis.Y:
  84056. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  84057. break;
  84058. case JoystickAxis.Z:
  84059. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  84060. break;
  84061. }
  84062. }
  84063. else {
  84064. var data = this._touches.get(e.pointerId.toString());
  84065. if (data) {
  84066. data.x = e.clientX;
  84067. data.y = e.clientY;
  84068. }
  84069. }
  84070. };
  84071. VirtualJoystick.prototype._onPointerUp = function (e) {
  84072. if (this._joystickPointerID == e.pointerId) {
  84073. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  84074. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  84075. this._joystickPointerID = -1;
  84076. this.pressed = false;
  84077. }
  84078. else {
  84079. var touch = this._touches.get(e.pointerId.toString());
  84080. if (touch) {
  84081. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84082. }
  84083. }
  84084. this._deltaJoystickVector.x = 0;
  84085. this._deltaJoystickVector.y = 0;
  84086. this._touches.remove(e.pointerId.toString());
  84087. };
  84088. /**
  84089. * Change the color of the virtual joystick
  84090. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  84091. */
  84092. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  84093. this._joystickColor = newColor;
  84094. };
  84095. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  84096. this._action = action;
  84097. };
  84098. // Define which axis you'd like to control for left & right
  84099. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  84100. switch (axis) {
  84101. case JoystickAxis.X:
  84102. case JoystickAxis.Y:
  84103. case JoystickAxis.Z:
  84104. this._axisTargetedByLeftAndRight = axis;
  84105. break;
  84106. default:
  84107. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84108. break;
  84109. }
  84110. };
  84111. // Define which axis you'd like to control for up & down
  84112. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  84113. switch (axis) {
  84114. case JoystickAxis.X:
  84115. case JoystickAxis.Y:
  84116. case JoystickAxis.Z:
  84117. this._axisTargetedByUpAndDown = axis;
  84118. break;
  84119. default:
  84120. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84121. break;
  84122. }
  84123. };
  84124. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  84125. var _this = this;
  84126. if (this.pressed) {
  84127. this._touches.forEach(function (key, touch) {
  84128. if (touch.pointerId === _this._joystickPointerID) {
  84129. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  84130. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  84131. VirtualJoystick.vjCanvasContext.beginPath();
  84132. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84133. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84134. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  84135. VirtualJoystick.vjCanvasContext.stroke();
  84136. VirtualJoystick.vjCanvasContext.closePath();
  84137. VirtualJoystick.vjCanvasContext.beginPath();
  84138. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84139. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84140. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  84141. VirtualJoystick.vjCanvasContext.stroke();
  84142. VirtualJoystick.vjCanvasContext.closePath();
  84143. VirtualJoystick.vjCanvasContext.beginPath();
  84144. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84145. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  84146. VirtualJoystick.vjCanvasContext.stroke();
  84147. VirtualJoystick.vjCanvasContext.closePath();
  84148. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  84149. }
  84150. else {
  84151. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84152. VirtualJoystick.vjCanvasContext.beginPath();
  84153. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  84154. VirtualJoystick.vjCanvasContext.beginPath();
  84155. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  84156. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84157. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  84158. VirtualJoystick.vjCanvasContext.stroke();
  84159. VirtualJoystick.vjCanvasContext.closePath();
  84160. touch.prevX = touch.x;
  84161. touch.prevY = touch.y;
  84162. }
  84163. ;
  84164. });
  84165. }
  84166. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84167. };
  84168. VirtualJoystick.prototype.releaseCanvas = function () {
  84169. if (VirtualJoystick.vjCanvas) {
  84170. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  84171. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  84172. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  84173. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  84174. window.removeEventListener("resize", this._onResize);
  84175. document.body.removeChild(VirtualJoystick.vjCanvas);
  84176. VirtualJoystick.vjCanvas = null;
  84177. }
  84178. };
  84179. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  84180. VirtualJoystick._globalJoystickIndex = 0;
  84181. return VirtualJoystick;
  84182. }());
  84183. BABYLON.VirtualJoystick = VirtualJoystick;
  84184. })(BABYLON || (BABYLON = {}));
  84185. //# sourceMappingURL=babylon.virtualJoystick.js.map
  84186. "use strict";
  84187. var BABYLON;
  84188. (function (BABYLON) {
  84189. // We're mainly based on the logic defined into the FreeCamera code
  84190. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  84191. __extends(VirtualJoysticksCamera, _super);
  84192. function VirtualJoysticksCamera(name, position, scene) {
  84193. var _this = _super.call(this, name, position, scene) || this;
  84194. _this.inputs.addVirtualJoystick();
  84195. return _this;
  84196. }
  84197. VirtualJoysticksCamera.prototype.getClassName = function () {
  84198. return "VirtualJoysticksCamera";
  84199. };
  84200. return VirtualJoysticksCamera;
  84201. }(BABYLON.FreeCamera));
  84202. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  84203. })(BABYLON || (BABYLON = {}));
  84204. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  84205. "use strict";
  84206. var BABYLON;
  84207. (function (BABYLON) {
  84208. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  84209. function FreeCameraVirtualJoystickInput() {
  84210. }
  84211. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  84212. return this._leftjoystick;
  84213. };
  84214. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  84215. return this._rightjoystick;
  84216. };
  84217. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  84218. if (this._leftjoystick) {
  84219. var camera = this.camera;
  84220. var speed = camera._computeLocalCameraSpeed() * 50;
  84221. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  84222. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  84223. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  84224. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  84225. if (!this._leftjoystick.pressed) {
  84226. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  84227. }
  84228. if (!this._rightjoystick.pressed) {
  84229. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  84230. }
  84231. }
  84232. };
  84233. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  84234. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  84235. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  84236. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  84237. this._leftjoystick.setJoystickSensibility(0.15);
  84238. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  84239. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  84240. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  84241. this._rightjoystick.reverseUpDown = true;
  84242. this._rightjoystick.setJoystickSensibility(0.05);
  84243. this._rightjoystick.setJoystickColor("yellow");
  84244. };
  84245. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  84246. this._leftjoystick.releaseCanvas();
  84247. this._rightjoystick.releaseCanvas();
  84248. };
  84249. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  84250. return "FreeCameraVirtualJoystickInput";
  84251. };
  84252. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  84253. return "virtualJoystick";
  84254. };
  84255. return FreeCameraVirtualJoystickInput;
  84256. }());
  84257. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  84258. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  84259. })(BABYLON || (BABYLON = {}));
  84260. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  84261. "use strict";
  84262. var BABYLON;
  84263. (function (BABYLON) {
  84264. var SimplificationSettings = /** @class */ (function () {
  84265. function SimplificationSettings(quality, distance, optimizeMesh) {
  84266. this.quality = quality;
  84267. this.distance = distance;
  84268. this.optimizeMesh = optimizeMesh;
  84269. }
  84270. return SimplificationSettings;
  84271. }());
  84272. BABYLON.SimplificationSettings = SimplificationSettings;
  84273. var SimplificationQueue = /** @class */ (function () {
  84274. function SimplificationQueue() {
  84275. this.running = false;
  84276. this._simplificationArray = [];
  84277. }
  84278. SimplificationQueue.prototype.addTask = function (task) {
  84279. this._simplificationArray.push(task);
  84280. };
  84281. SimplificationQueue.prototype.executeNext = function () {
  84282. var task = this._simplificationArray.pop();
  84283. if (task) {
  84284. this.running = true;
  84285. this.runSimplification(task);
  84286. }
  84287. else {
  84288. this.running = false;
  84289. }
  84290. };
  84291. SimplificationQueue.prototype.runSimplification = function (task) {
  84292. var _this = this;
  84293. if (task.parallelProcessing) {
  84294. //parallel simplifier
  84295. task.settings.forEach(function (setting) {
  84296. var simplifier = _this.getSimplifier(task);
  84297. simplifier.simplify(setting, function (newMesh) {
  84298. task.mesh.addLODLevel(setting.distance, newMesh);
  84299. newMesh.isVisible = true;
  84300. //check if it is the last
  84301. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  84302. //all done, run the success callback.
  84303. task.successCallback();
  84304. }
  84305. _this.executeNext();
  84306. });
  84307. });
  84308. }
  84309. else {
  84310. //single simplifier.
  84311. var simplifier = this.getSimplifier(task);
  84312. var runDecimation = function (setting, callback) {
  84313. simplifier.simplify(setting, function (newMesh) {
  84314. task.mesh.addLODLevel(setting.distance, newMesh);
  84315. newMesh.isVisible = true;
  84316. //run the next quality level
  84317. callback();
  84318. });
  84319. };
  84320. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  84321. runDecimation(task.settings[loop.index], function () {
  84322. loop.executeNext();
  84323. });
  84324. }, function () {
  84325. //execution ended, run the success callback.
  84326. if (task.successCallback) {
  84327. task.successCallback();
  84328. }
  84329. _this.executeNext();
  84330. });
  84331. }
  84332. };
  84333. SimplificationQueue.prototype.getSimplifier = function (task) {
  84334. switch (task.simplificationType) {
  84335. case SimplificationType.QUADRATIC:
  84336. default:
  84337. return new QuadraticErrorSimplification(task.mesh);
  84338. }
  84339. };
  84340. return SimplificationQueue;
  84341. }());
  84342. BABYLON.SimplificationQueue = SimplificationQueue;
  84343. /**
  84344. * The implemented types of simplification.
  84345. * At the moment only Quadratic Error Decimation is implemented.
  84346. */
  84347. var SimplificationType;
  84348. (function (SimplificationType) {
  84349. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  84350. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  84351. var DecimationTriangle = /** @class */ (function () {
  84352. function DecimationTriangle(vertices) {
  84353. this.vertices = vertices;
  84354. this.error = new Array(4);
  84355. this.deleted = false;
  84356. this.isDirty = false;
  84357. this.deletePending = false;
  84358. this.borderFactor = 0;
  84359. }
  84360. return DecimationTriangle;
  84361. }());
  84362. BABYLON.DecimationTriangle = DecimationTriangle;
  84363. var DecimationVertex = /** @class */ (function () {
  84364. function DecimationVertex(position, id) {
  84365. this.position = position;
  84366. this.id = id;
  84367. this.isBorder = true;
  84368. this.q = new QuadraticMatrix();
  84369. this.triangleCount = 0;
  84370. this.triangleStart = 0;
  84371. this.originalOffsets = [];
  84372. }
  84373. DecimationVertex.prototype.updatePosition = function (newPosition) {
  84374. this.position.copyFrom(newPosition);
  84375. };
  84376. return DecimationVertex;
  84377. }());
  84378. BABYLON.DecimationVertex = DecimationVertex;
  84379. var QuadraticMatrix = /** @class */ (function () {
  84380. function QuadraticMatrix(data) {
  84381. this.data = new Array(10);
  84382. for (var i = 0; i < 10; ++i) {
  84383. if (data && data[i]) {
  84384. this.data[i] = data[i];
  84385. }
  84386. else {
  84387. this.data[i] = 0;
  84388. }
  84389. }
  84390. }
  84391. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  84392. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  84393. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  84394. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  84395. return det;
  84396. };
  84397. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  84398. for (var i = 0; i < 10; ++i) {
  84399. this.data[i] += matrix.data[i];
  84400. }
  84401. };
  84402. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  84403. for (var i = 0; i < 10; ++i) {
  84404. this.data[i] += data[i];
  84405. }
  84406. };
  84407. QuadraticMatrix.prototype.add = function (matrix) {
  84408. var m = new QuadraticMatrix();
  84409. for (var i = 0; i < 10; ++i) {
  84410. m.data[i] = this.data[i] + matrix.data[i];
  84411. }
  84412. return m;
  84413. };
  84414. QuadraticMatrix.FromData = function (a, b, c, d) {
  84415. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  84416. };
  84417. //returning an array to avoid garbage collection
  84418. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  84419. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  84420. };
  84421. return QuadraticMatrix;
  84422. }());
  84423. BABYLON.QuadraticMatrix = QuadraticMatrix;
  84424. var Reference = /** @class */ (function () {
  84425. function Reference(vertexId, triangleId) {
  84426. this.vertexId = vertexId;
  84427. this.triangleId = triangleId;
  84428. }
  84429. return Reference;
  84430. }());
  84431. BABYLON.Reference = Reference;
  84432. /**
  84433. * An implementation of the Quadratic Error simplification algorithm.
  84434. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  84435. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  84436. * @author RaananW
  84437. */
  84438. var QuadraticErrorSimplification = /** @class */ (function () {
  84439. function QuadraticErrorSimplification(_mesh) {
  84440. this._mesh = _mesh;
  84441. this.syncIterations = 5000;
  84442. this.aggressiveness = 7;
  84443. this.decimationIterations = 100;
  84444. this.boundingBoxEpsilon = BABYLON.Epsilon;
  84445. }
  84446. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  84447. var _this = this;
  84448. this.initDecimatedMesh();
  84449. //iterating through the submeshes array, one after the other.
  84450. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  84451. _this.initWithMesh(loop.index, function () {
  84452. _this.runDecimation(settings, loop.index, function () {
  84453. loop.executeNext();
  84454. });
  84455. }, settings.optimizeMesh);
  84456. }, function () {
  84457. setTimeout(function () {
  84458. successCallback(_this._reconstructedMesh);
  84459. }, 0);
  84460. });
  84461. };
  84462. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  84463. var _this = this;
  84464. var targetCount = ~~(this.triangles.length * settings.quality);
  84465. var deletedTriangles = 0;
  84466. var triangleCount = this.triangles.length;
  84467. var iterationFunction = function (iteration, callback) {
  84468. setTimeout(function () {
  84469. if (iteration % 5 === 0) {
  84470. _this.updateMesh(iteration === 0);
  84471. }
  84472. for (var i = 0; i < _this.triangles.length; ++i) {
  84473. _this.triangles[i].isDirty = false;
  84474. }
  84475. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  84476. var trianglesIterator = function (i) {
  84477. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  84478. var t = _this.triangles[tIdx];
  84479. if (!t)
  84480. return;
  84481. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  84482. return;
  84483. }
  84484. for (var j = 0; j < 3; ++j) {
  84485. if (t.error[j] < threshold) {
  84486. var deleted0 = [];
  84487. var deleted1 = [];
  84488. var v0 = t.vertices[j];
  84489. var v1 = t.vertices[(j + 1) % 3];
  84490. if (v0.isBorder || v1.isBorder)
  84491. continue;
  84492. var p = BABYLON.Vector3.Zero();
  84493. var n = BABYLON.Vector3.Zero();
  84494. var uv = BABYLON.Vector2.Zero();
  84495. var color = new BABYLON.Color4(0, 0, 0, 1);
  84496. _this.calculateError(v0, v1, p, n, uv, color);
  84497. var delTr = new Array();
  84498. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  84499. continue;
  84500. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  84501. continue;
  84502. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  84503. continue;
  84504. var uniqueArray = new Array();
  84505. delTr.forEach(function (deletedT) {
  84506. if (uniqueArray.indexOf(deletedT) === -1) {
  84507. deletedT.deletePending = true;
  84508. uniqueArray.push(deletedT);
  84509. }
  84510. });
  84511. if (uniqueArray.length % 2 !== 0) {
  84512. continue;
  84513. }
  84514. v0.q = v1.q.add(v0.q);
  84515. v0.updatePosition(p);
  84516. var tStart = _this.references.length;
  84517. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  84518. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  84519. var tCount = _this.references.length - tStart;
  84520. if (tCount <= v0.triangleCount) {
  84521. if (tCount) {
  84522. for (var c = 0; c < tCount; c++) {
  84523. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  84524. }
  84525. }
  84526. }
  84527. else {
  84528. v0.triangleStart = tStart;
  84529. }
  84530. v0.triangleCount = tCount;
  84531. break;
  84532. }
  84533. }
  84534. };
  84535. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  84536. }, 0);
  84537. };
  84538. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  84539. if (triangleCount - deletedTriangles <= targetCount)
  84540. loop.breakLoop();
  84541. else {
  84542. iterationFunction(loop.index, function () {
  84543. loop.executeNext();
  84544. });
  84545. }
  84546. }, function () {
  84547. setTimeout(function () {
  84548. //reconstruct this part of the mesh
  84549. _this.reconstructMesh(submeshIndex);
  84550. successCallback();
  84551. }, 0);
  84552. });
  84553. };
  84554. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  84555. var _this = this;
  84556. this.vertices = [];
  84557. this.triangles = [];
  84558. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84559. var indices = this._mesh.getIndices();
  84560. var submesh = this._mesh.subMeshes[submeshIndex];
  84561. var findInVertices = function (positionToSearch) {
  84562. if (optimizeMesh) {
  84563. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  84564. if (_this.vertices[ii].position.equals(positionToSearch)) {
  84565. return _this.vertices[ii];
  84566. }
  84567. }
  84568. }
  84569. return null;
  84570. };
  84571. var vertexReferences = [];
  84572. var vertexInit = function (i) {
  84573. if (!positionData) {
  84574. return;
  84575. }
  84576. var offset = i + submesh.verticesStart;
  84577. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  84578. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  84579. vertex.originalOffsets.push(offset);
  84580. if (vertex.id === _this.vertices.length) {
  84581. _this.vertices.push(vertex);
  84582. }
  84583. vertexReferences.push(vertex.id);
  84584. };
  84585. //var totalVertices = mesh.getTotalVertices();
  84586. var totalVertices = submesh.verticesCount;
  84587. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  84588. var indicesInit = function (i) {
  84589. if (!indices) {
  84590. return;
  84591. }
  84592. var offset = (submesh.indexStart / 3) + i;
  84593. var pos = (offset * 3);
  84594. var i0 = indices[pos + 0];
  84595. var i1 = indices[pos + 1];
  84596. var i2 = indices[pos + 2];
  84597. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  84598. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  84599. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  84600. var triangle = new DecimationTriangle([v0, v1, v2]);
  84601. triangle.originalOffset = pos;
  84602. _this.triangles.push(triangle);
  84603. };
  84604. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  84605. _this.init(callback);
  84606. });
  84607. });
  84608. };
  84609. QuadraticErrorSimplification.prototype.init = function (callback) {
  84610. var _this = this;
  84611. var triangleInit1 = function (i) {
  84612. var t = _this.triangles[i];
  84613. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  84614. for (var j = 0; j < 3; j++) {
  84615. 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))));
  84616. }
  84617. };
  84618. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  84619. var triangleInit2 = function (i) {
  84620. var t = _this.triangles[i];
  84621. for (var j = 0; j < 3; ++j) {
  84622. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  84623. }
  84624. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84625. };
  84626. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  84627. callback();
  84628. });
  84629. });
  84630. };
  84631. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  84632. var newTriangles = [];
  84633. var i;
  84634. for (i = 0; i < this.vertices.length; ++i) {
  84635. this.vertices[i].triangleCount = 0;
  84636. }
  84637. var t;
  84638. var j;
  84639. for (i = 0; i < this.triangles.length; ++i) {
  84640. if (!this.triangles[i].deleted) {
  84641. t = this.triangles[i];
  84642. for (j = 0; j < 3; ++j) {
  84643. t.vertices[j].triangleCount = 1;
  84644. }
  84645. newTriangles.push(t);
  84646. }
  84647. }
  84648. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  84649. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  84650. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  84651. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  84652. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  84653. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  84654. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  84655. var vertexCount = 0;
  84656. for (i = 0; i < this.vertices.length; ++i) {
  84657. var vertex = this.vertices[i];
  84658. vertex.id = vertexCount;
  84659. if (vertex.triangleCount) {
  84660. vertex.originalOffsets.forEach(function (originalOffset) {
  84661. if (!normalData) {
  84662. return;
  84663. }
  84664. newPositionData.push(vertex.position.x);
  84665. newPositionData.push(vertex.position.y);
  84666. newPositionData.push(vertex.position.z);
  84667. newNormalData.push(normalData[originalOffset * 3]);
  84668. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  84669. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  84670. if (uvs && uvs.length) {
  84671. newUVsData.push(uvs[(originalOffset * 2)]);
  84672. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  84673. }
  84674. else if (colorsData && colorsData.length) {
  84675. newColorsData.push(colorsData[(originalOffset * 4)]);
  84676. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  84677. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  84678. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  84679. }
  84680. ++vertexCount;
  84681. });
  84682. }
  84683. }
  84684. var startingIndex = this._reconstructedMesh.getTotalIndices();
  84685. var startingVertex = this._reconstructedMesh.getTotalVertices();
  84686. var submeshesArray = this._reconstructedMesh.subMeshes;
  84687. this._reconstructedMesh.subMeshes = [];
  84688. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  84689. var originalIndices = this._mesh.getIndices();
  84690. for (i = 0; i < newTriangles.length; ++i) {
  84691. t = newTriangles[i]; //now get the new referencing point for each vertex
  84692. [0, 1, 2].forEach(function (idx) {
  84693. var id = originalIndices[t.originalOffset + idx];
  84694. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  84695. if (offset < 0)
  84696. offset = 0;
  84697. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  84698. });
  84699. }
  84700. //overwriting the old vertex buffers and indices.
  84701. this._reconstructedMesh.setIndices(newIndicesArray);
  84702. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  84703. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  84704. if (newUVsData.length > 0)
  84705. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  84706. if (newColorsData.length > 0)
  84707. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  84708. //create submesh
  84709. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  84710. if (submeshIndex > 0) {
  84711. this._reconstructedMesh.subMeshes = [];
  84712. submeshesArray.forEach(function (submesh) {
  84713. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  84714. });
  84715. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  84716. }
  84717. };
  84718. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  84719. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  84720. this._reconstructedMesh.material = this._mesh.material;
  84721. this._reconstructedMesh.parent = this._mesh.parent;
  84722. this._reconstructedMesh.isVisible = false;
  84723. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  84724. };
  84725. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  84726. for (var i = 0; i < vertex1.triangleCount; ++i) {
  84727. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  84728. if (t.deleted)
  84729. continue;
  84730. var s = this.references[vertex1.triangleStart + i].vertexId;
  84731. var v1 = t.vertices[(s + 1) % 3];
  84732. var v2 = t.vertices[(s + 2) % 3];
  84733. if ((v1 === vertex2 || v2 === vertex2)) {
  84734. deletedArray[i] = true;
  84735. delTr.push(t);
  84736. continue;
  84737. }
  84738. var d1 = v1.position.subtract(point);
  84739. d1 = d1.normalize();
  84740. var d2 = v2.position.subtract(point);
  84741. d2 = d2.normalize();
  84742. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  84743. return true;
  84744. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  84745. deletedArray[i] = false;
  84746. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  84747. return true;
  84748. }
  84749. return false;
  84750. };
  84751. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  84752. var newDeleted = deletedTriangles;
  84753. for (var i = 0; i < vertex.triangleCount; ++i) {
  84754. var ref = this.references[vertex.triangleStart + i];
  84755. var t = this.triangles[ref.triangleId];
  84756. if (t.deleted)
  84757. continue;
  84758. if (deletedArray[i] && t.deletePending) {
  84759. t.deleted = true;
  84760. newDeleted++;
  84761. continue;
  84762. }
  84763. t.vertices[ref.vertexId] = origVertex;
  84764. t.isDirty = true;
  84765. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  84766. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  84767. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  84768. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84769. this.references.push(ref);
  84770. }
  84771. return newDeleted;
  84772. };
  84773. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  84774. for (var i = 0; i < this.vertices.length; ++i) {
  84775. var vCount = [];
  84776. var vId = [];
  84777. var v = this.vertices[i];
  84778. var j;
  84779. for (j = 0; j < v.triangleCount; ++j) {
  84780. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  84781. for (var ii = 0; ii < 3; ii++) {
  84782. var ofs = 0;
  84783. var vv = triangle.vertices[ii];
  84784. while (ofs < vCount.length) {
  84785. if (vId[ofs] === vv.id)
  84786. break;
  84787. ++ofs;
  84788. }
  84789. if (ofs === vCount.length) {
  84790. vCount.push(1);
  84791. vId.push(vv.id);
  84792. }
  84793. else {
  84794. vCount[ofs]++;
  84795. }
  84796. }
  84797. }
  84798. for (j = 0; j < vCount.length; ++j) {
  84799. if (vCount[j] === 1) {
  84800. this.vertices[vId[j]].isBorder = true;
  84801. }
  84802. else {
  84803. this.vertices[vId[j]].isBorder = false;
  84804. }
  84805. }
  84806. }
  84807. };
  84808. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  84809. if (identifyBorders === void 0) { identifyBorders = false; }
  84810. var i;
  84811. if (!identifyBorders) {
  84812. var newTrianglesVector = [];
  84813. for (i = 0; i < this.triangles.length; ++i) {
  84814. if (!this.triangles[i].deleted) {
  84815. newTrianglesVector.push(this.triangles[i]);
  84816. }
  84817. }
  84818. this.triangles = newTrianglesVector;
  84819. }
  84820. for (i = 0; i < this.vertices.length; ++i) {
  84821. this.vertices[i].triangleCount = 0;
  84822. this.vertices[i].triangleStart = 0;
  84823. }
  84824. var t;
  84825. var j;
  84826. var v;
  84827. for (i = 0; i < this.triangles.length; ++i) {
  84828. t = this.triangles[i];
  84829. for (j = 0; j < 3; ++j) {
  84830. v = t.vertices[j];
  84831. v.triangleCount++;
  84832. }
  84833. }
  84834. var tStart = 0;
  84835. for (i = 0; i < this.vertices.length; ++i) {
  84836. this.vertices[i].triangleStart = tStart;
  84837. tStart += this.vertices[i].triangleCount;
  84838. this.vertices[i].triangleCount = 0;
  84839. }
  84840. var newReferences = new Array(this.triangles.length * 3);
  84841. for (i = 0; i < this.triangles.length; ++i) {
  84842. t = this.triangles[i];
  84843. for (j = 0; j < 3; ++j) {
  84844. v = t.vertices[j];
  84845. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  84846. v.triangleCount++;
  84847. }
  84848. }
  84849. this.references = newReferences;
  84850. if (identifyBorders) {
  84851. this.identifyBorder();
  84852. }
  84853. };
  84854. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  84855. var x = point.x;
  84856. var y = point.y;
  84857. var z = point.z;
  84858. 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
  84859. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  84860. };
  84861. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  84862. var q = vertex1.q.add(vertex2.q);
  84863. var border = vertex1.isBorder && vertex2.isBorder;
  84864. var error = 0;
  84865. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  84866. if (qDet !== 0 && !border) {
  84867. if (!pointResult) {
  84868. pointResult = BABYLON.Vector3.Zero();
  84869. }
  84870. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  84871. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  84872. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  84873. error = this.vertexError(q, pointResult);
  84874. }
  84875. else {
  84876. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  84877. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  84878. var error1 = this.vertexError(q, vertex1.position);
  84879. var error2 = this.vertexError(q, vertex2.position);
  84880. var error3 = this.vertexError(q, p3);
  84881. error = Math.min(error1, error2, error3);
  84882. if (error === error1) {
  84883. if (pointResult) {
  84884. pointResult.copyFrom(vertex1.position);
  84885. }
  84886. }
  84887. else if (error === error2) {
  84888. if (pointResult) {
  84889. pointResult.copyFrom(vertex2.position);
  84890. }
  84891. }
  84892. else {
  84893. if (pointResult) {
  84894. pointResult.copyFrom(p3);
  84895. }
  84896. }
  84897. }
  84898. return error;
  84899. };
  84900. return QuadraticErrorSimplification;
  84901. }());
  84902. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  84903. })(BABYLON || (BABYLON = {}));
  84904. //# sourceMappingURL=babylon.meshSimplification.js.map
  84905. "use strict";
  84906. var BABYLON;
  84907. (function (BABYLON) {
  84908. var MeshLODLevel = /** @class */ (function () {
  84909. function MeshLODLevel(distance, mesh) {
  84910. this.distance = distance;
  84911. this.mesh = mesh;
  84912. }
  84913. return MeshLODLevel;
  84914. }());
  84915. BABYLON.MeshLODLevel = MeshLODLevel;
  84916. })(BABYLON || (BABYLON = {}));
  84917. //# sourceMappingURL=babylon.meshLODLevel.js.map
  84918. "use strict";
  84919. var BABYLON;
  84920. (function (BABYLON) {
  84921. /**
  84922. * Defines the root class used to create scene optimization to use with SceneOptimizer
  84923. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84924. */
  84925. var SceneOptimization = /** @class */ (function () {
  84926. /**
  84927. * Creates the SceneOptimization object
  84928. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84929. * @param desc defines the description associated with the optimization
  84930. */
  84931. function SceneOptimization(
  84932. /**
  84933. * Defines the priority of this optimization (0 by default which means first in the list)
  84934. */
  84935. priority) {
  84936. if (priority === void 0) { priority = 0; }
  84937. this.priority = priority;
  84938. }
  84939. /**
  84940. * Gets a string describing the action executed by the current optimization
  84941. * @returns description string
  84942. */
  84943. SceneOptimization.prototype.getDescription = function () {
  84944. return "";
  84945. };
  84946. /**
  84947. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84948. * @param scene defines the current scene where to apply this optimization
  84949. * @param optimizer defines the current optimizer
  84950. * @returns true if everything that can be done was applied
  84951. */
  84952. SceneOptimization.prototype.apply = function (scene, optimizer) {
  84953. return true;
  84954. };
  84955. ;
  84956. return SceneOptimization;
  84957. }());
  84958. BABYLON.SceneOptimization = SceneOptimization;
  84959. /**
  84960. * Defines an optimization used to reduce the size of render target textures
  84961. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84962. */
  84963. var TextureOptimization = /** @class */ (function (_super) {
  84964. __extends(TextureOptimization, _super);
  84965. /**
  84966. * Creates the TextureOptimization object
  84967. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84968. * @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
  84969. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84970. */
  84971. function TextureOptimization(
  84972. /**
  84973. * Defines the priority of this optimization (0 by default which means first in the list)
  84974. */
  84975. priority,
  84976. /**
  84977. * 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
  84978. */
  84979. maximumSize,
  84980. /**
  84981. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84982. */
  84983. step) {
  84984. if (priority === void 0) { priority = 0; }
  84985. if (maximumSize === void 0) { maximumSize = 1024; }
  84986. if (step === void 0) { step = 0.5; }
  84987. var _this = _super.call(this, priority) || this;
  84988. _this.priority = priority;
  84989. _this.maximumSize = maximumSize;
  84990. _this.step = step;
  84991. return _this;
  84992. }
  84993. /**
  84994. * Gets a string describing the action executed by the current optimization
  84995. * @returns description string
  84996. */
  84997. TextureOptimization.prototype.getDescription = function () {
  84998. return "Reducing render target texture size to " + this.maximumSize;
  84999. };
  85000. /**
  85001. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85002. * @param scene defines the current scene where to apply this optimization
  85003. * @param optimizer defines the current optimizer
  85004. * @returns true if everything that can be done was applied
  85005. */
  85006. TextureOptimization.prototype.apply = function (scene, optimizer) {
  85007. var allDone = true;
  85008. for (var index = 0; index < scene.textures.length; index++) {
  85009. var texture = scene.textures[index];
  85010. if (!texture.canRescale || texture.getContext) {
  85011. continue;
  85012. }
  85013. var currentSize = texture.getSize();
  85014. var maxDimension = Math.max(currentSize.width, currentSize.height);
  85015. if (maxDimension > this.maximumSize) {
  85016. texture.scale(this.step);
  85017. allDone = false;
  85018. }
  85019. }
  85020. return allDone;
  85021. };
  85022. return TextureOptimization;
  85023. }(SceneOptimization));
  85024. BABYLON.TextureOptimization = TextureOptimization;
  85025. /**
  85026. * Defines an optimization used to increase or decrease the rendering resolution
  85027. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85028. */
  85029. var HardwareScalingOptimization = /** @class */ (function (_super) {
  85030. __extends(HardwareScalingOptimization, _super);
  85031. /**
  85032. * Creates the HardwareScalingOptimization object
  85033. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85034. * @param maximumScale defines the maximum scale to use (2 by default)
  85035. * @param step defines the step to use between two passes (0.5 by default)
  85036. */
  85037. function HardwareScalingOptimization(
  85038. /**
  85039. * Defines the priority of this optimization (0 by default which means first in the list)
  85040. */
  85041. priority,
  85042. /**
  85043. * Defines the maximum scale to use (2 by default)
  85044. */
  85045. maximumScale,
  85046. /**
  85047. * Defines the step to use between two passes (0.5 by default)
  85048. */
  85049. step) {
  85050. if (priority === void 0) { priority = 0; }
  85051. if (maximumScale === void 0) { maximumScale = 2; }
  85052. if (step === void 0) { step = 0.25; }
  85053. var _this = _super.call(this, priority) || this;
  85054. _this.priority = priority;
  85055. _this.maximumScale = maximumScale;
  85056. _this.step = step;
  85057. _this._currentScale = -1;
  85058. _this._directionOffset = 1;
  85059. return _this;
  85060. }
  85061. /**
  85062. * Gets a string describing the action executed by the current optimization
  85063. * @return description string
  85064. */
  85065. HardwareScalingOptimization.prototype.getDescription = function () {
  85066. return "Setting hardware scaling level to " + this._currentScale;
  85067. };
  85068. /**
  85069. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85070. * @param scene defines the current scene where to apply this optimization
  85071. * @param optimizer defines the current optimizer
  85072. * @returns true if everything that can be done was applied
  85073. */
  85074. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  85075. if (this._currentScale === -1) {
  85076. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  85077. if (this._currentScale > this.maximumScale) {
  85078. this._directionOffset = -1;
  85079. }
  85080. }
  85081. this._currentScale += this._directionOffset * this.step;
  85082. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  85083. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  85084. };
  85085. ;
  85086. return HardwareScalingOptimization;
  85087. }(SceneOptimization));
  85088. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  85089. /**
  85090. * Defines an optimization used to remove shadows
  85091. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85092. */
  85093. var ShadowsOptimization = /** @class */ (function (_super) {
  85094. __extends(ShadowsOptimization, _super);
  85095. function ShadowsOptimization() {
  85096. return _super !== null && _super.apply(this, arguments) || this;
  85097. }
  85098. /**
  85099. * Gets a string describing the action executed by the current optimization
  85100. * @return description string
  85101. */
  85102. ShadowsOptimization.prototype.getDescription = function () {
  85103. return "Turning shadows on/off";
  85104. };
  85105. /**
  85106. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85107. * @param scene defines the current scene where to apply this optimization
  85108. * @param optimizer defines the current optimizer
  85109. * @returns true if everything that can be done was applied
  85110. */
  85111. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  85112. scene.shadowsEnabled = optimizer.isInImprovementMode;
  85113. return true;
  85114. };
  85115. ;
  85116. return ShadowsOptimization;
  85117. }(SceneOptimization));
  85118. BABYLON.ShadowsOptimization = ShadowsOptimization;
  85119. /**
  85120. * Defines an optimization used to turn post-processes off
  85121. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85122. */
  85123. var PostProcessesOptimization = /** @class */ (function (_super) {
  85124. __extends(PostProcessesOptimization, _super);
  85125. function PostProcessesOptimization() {
  85126. return _super !== null && _super.apply(this, arguments) || this;
  85127. }
  85128. /**
  85129. * Gets a string describing the action executed by the current optimization
  85130. * @return description string
  85131. */
  85132. PostProcessesOptimization.prototype.getDescription = function () {
  85133. return "Turning post-processes on/off";
  85134. };
  85135. /**
  85136. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85137. * @param scene defines the current scene where to apply this optimization
  85138. * @param optimizer defines the current optimizer
  85139. * @returns true if everything that can be done was applied
  85140. */
  85141. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  85142. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  85143. return true;
  85144. };
  85145. ;
  85146. return PostProcessesOptimization;
  85147. }(SceneOptimization));
  85148. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  85149. /**
  85150. * Defines an optimization used to turn lens flares off
  85151. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85152. */
  85153. var LensFlaresOptimization = /** @class */ (function (_super) {
  85154. __extends(LensFlaresOptimization, _super);
  85155. function LensFlaresOptimization() {
  85156. return _super !== null && _super.apply(this, arguments) || this;
  85157. }
  85158. /**
  85159. * Gets a string describing the action executed by the current optimization
  85160. * @return description string
  85161. */
  85162. LensFlaresOptimization.prototype.getDescription = function () {
  85163. return "Turning lens flares on/off";
  85164. };
  85165. /**
  85166. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85167. * @param scene defines the current scene where to apply this optimization
  85168. * @param optimizer defines the current optimizer
  85169. * @returns true if everything that can be done was applied
  85170. */
  85171. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  85172. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  85173. return true;
  85174. };
  85175. ;
  85176. return LensFlaresOptimization;
  85177. }(SceneOptimization));
  85178. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  85179. /**
  85180. * Defines an optimization based on user defined callback.
  85181. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85182. */
  85183. var CustomOptimization = /** @class */ (function (_super) {
  85184. __extends(CustomOptimization, _super);
  85185. function CustomOptimization() {
  85186. return _super !== null && _super.apply(this, arguments) || this;
  85187. }
  85188. /**
  85189. * Gets a string describing the action executed by the current optimization
  85190. * @returns description string
  85191. */
  85192. CustomOptimization.prototype.getDescription = function () {
  85193. if (this.onGetDescription) {
  85194. return this.onGetDescription();
  85195. }
  85196. return "Running user defined callback";
  85197. };
  85198. /**
  85199. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85200. * @param scene defines the current scene where to apply this optimization
  85201. * @param optimizer defines the current optimizer
  85202. * @returns true if everything that can be done was applied
  85203. */
  85204. CustomOptimization.prototype.apply = function (scene, optimizer) {
  85205. if (this.onApply) {
  85206. return this.onApply(scene, optimizer);
  85207. }
  85208. return true;
  85209. };
  85210. ;
  85211. return CustomOptimization;
  85212. }(SceneOptimization));
  85213. BABYLON.CustomOptimization = CustomOptimization;
  85214. /**
  85215. * Defines an optimization used to turn particles off
  85216. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85217. */
  85218. var ParticlesOptimization = /** @class */ (function (_super) {
  85219. __extends(ParticlesOptimization, _super);
  85220. function ParticlesOptimization() {
  85221. return _super !== null && _super.apply(this, arguments) || this;
  85222. }
  85223. /**
  85224. * Gets a string describing the action executed by the current optimization
  85225. * @return description string
  85226. */
  85227. ParticlesOptimization.prototype.getDescription = function () {
  85228. return "Turning particles on/off";
  85229. };
  85230. /**
  85231. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85232. * @param scene defines the current scene where to apply this optimization
  85233. * @param optimizer defines the current optimizer
  85234. * @returns true if everything that can be done was applied
  85235. */
  85236. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  85237. scene.particlesEnabled = optimizer.isInImprovementMode;
  85238. return true;
  85239. };
  85240. ;
  85241. return ParticlesOptimization;
  85242. }(SceneOptimization));
  85243. BABYLON.ParticlesOptimization = ParticlesOptimization;
  85244. /**
  85245. * Defines an optimization used to turn render targets off
  85246. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85247. */
  85248. var RenderTargetsOptimization = /** @class */ (function (_super) {
  85249. __extends(RenderTargetsOptimization, _super);
  85250. function RenderTargetsOptimization() {
  85251. return _super !== null && _super.apply(this, arguments) || this;
  85252. }
  85253. /**
  85254. * Gets a string describing the action executed by the current optimization
  85255. * @return description string
  85256. */
  85257. RenderTargetsOptimization.prototype.getDescription = function () {
  85258. return "Turning render targets off";
  85259. };
  85260. /**
  85261. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85262. * @param scene defines the current scene where to apply this optimization
  85263. * @param optimizer defines the current optimizer
  85264. * @returns true if everything that can be done was applied
  85265. */
  85266. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  85267. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  85268. return true;
  85269. };
  85270. ;
  85271. return RenderTargetsOptimization;
  85272. }(SceneOptimization));
  85273. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  85274. /**
  85275. * Defines an optimization used to merge meshes with compatible materials
  85276. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85277. */
  85278. var MergeMeshesOptimization = /** @class */ (function (_super) {
  85279. __extends(MergeMeshesOptimization, _super);
  85280. function MergeMeshesOptimization() {
  85281. var _this = _super !== null && _super.apply(this, arguments) || this;
  85282. _this._canBeMerged = function (abstractMesh) {
  85283. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  85284. return false;
  85285. }
  85286. var mesh = abstractMesh;
  85287. if (!mesh.isVisible || !mesh.isEnabled()) {
  85288. return false;
  85289. }
  85290. if (mesh.instances.length > 0) {
  85291. return false;
  85292. }
  85293. if (mesh.skeleton || mesh.hasLODLevels) {
  85294. return false;
  85295. }
  85296. if (mesh.parent) {
  85297. return false;
  85298. }
  85299. return true;
  85300. };
  85301. return _this;
  85302. }
  85303. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  85304. /**
  85305. * Gets or sets a boolean which defines if optimization octree has to be updated
  85306. */
  85307. get: function () {
  85308. return MergeMeshesOptimization._UpdateSelectionTree;
  85309. },
  85310. /**
  85311. * Gets or sets a boolean which defines if optimization octree has to be updated
  85312. */
  85313. set: function (value) {
  85314. MergeMeshesOptimization._UpdateSelectionTree = value;
  85315. },
  85316. enumerable: true,
  85317. configurable: true
  85318. });
  85319. /**
  85320. * Gets a string describing the action executed by the current optimization
  85321. * @return description string
  85322. */
  85323. MergeMeshesOptimization.prototype.getDescription = function () {
  85324. return "Merging similar meshes together";
  85325. };
  85326. /**
  85327. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85328. * @param scene defines the current scene where to apply this optimization
  85329. * @param optimizer defines the current optimizer
  85330. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  85331. * @returns true if everything that can be done was applied
  85332. */
  85333. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  85334. var globalPool = scene.meshes.slice(0);
  85335. var globalLength = globalPool.length;
  85336. for (var index = 0; index < globalLength; index++) {
  85337. var currentPool = new Array();
  85338. var current = globalPool[index];
  85339. // Checks
  85340. if (!this._canBeMerged(current)) {
  85341. continue;
  85342. }
  85343. currentPool.push(current);
  85344. // Find compatible meshes
  85345. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  85346. var otherMesh = globalPool[subIndex];
  85347. if (!this._canBeMerged(otherMesh)) {
  85348. continue;
  85349. }
  85350. if (otherMesh.material !== current.material) {
  85351. continue;
  85352. }
  85353. if (otherMesh.checkCollisions !== current.checkCollisions) {
  85354. continue;
  85355. }
  85356. currentPool.push(otherMesh);
  85357. globalLength--;
  85358. globalPool.splice(subIndex, 1);
  85359. subIndex--;
  85360. }
  85361. if (currentPool.length < 2) {
  85362. continue;
  85363. }
  85364. // Merge meshes
  85365. BABYLON.Mesh.MergeMeshes(currentPool);
  85366. }
  85367. if (updateSelectionTree != undefined) {
  85368. if (updateSelectionTree) {
  85369. scene.createOrUpdateSelectionOctree();
  85370. }
  85371. }
  85372. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  85373. scene.createOrUpdateSelectionOctree();
  85374. }
  85375. return true;
  85376. };
  85377. ;
  85378. MergeMeshesOptimization._UpdateSelectionTree = false;
  85379. return MergeMeshesOptimization;
  85380. }(SceneOptimization));
  85381. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  85382. /**
  85383. * Defines a list of options used by SceneOptimizer
  85384. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85385. */
  85386. var SceneOptimizerOptions = /** @class */ (function () {
  85387. /**
  85388. * Creates a new list of options used by SceneOptimizer
  85389. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  85390. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  85391. */
  85392. function SceneOptimizerOptions(
  85393. /**
  85394. * Defines the target frame rate to reach (60 by default)
  85395. */
  85396. targetFrameRate,
  85397. /**
  85398. * Defines the interval between two checkes (2000ms by default)
  85399. */
  85400. trackerDuration) {
  85401. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  85402. if (trackerDuration === void 0) { trackerDuration = 2000; }
  85403. this.targetFrameRate = targetFrameRate;
  85404. this.trackerDuration = trackerDuration;
  85405. /**
  85406. * Gets the list of optimizations to apply
  85407. */
  85408. this.optimizations = new Array();
  85409. }
  85410. /**
  85411. * Add a new optimization
  85412. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  85413. * @returns the current SceneOptimizerOptions
  85414. */
  85415. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  85416. this.optimizations.push(optimization);
  85417. return this;
  85418. };
  85419. /**
  85420. * Add a new custom optimization
  85421. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  85422. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  85423. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85424. * @returns the current SceneOptimizerOptions
  85425. */
  85426. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  85427. if (priority === void 0) { priority = 0; }
  85428. var optimization = new CustomOptimization(priority);
  85429. optimization.onApply = onApply;
  85430. optimization.onGetDescription = onGetDescription;
  85431. this.optimizations.push(optimization);
  85432. return this;
  85433. };
  85434. /**
  85435. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  85436. * @param targetFrameRate defines the target frame rate (60 by default)
  85437. * @returns a SceneOptimizerOptions object
  85438. */
  85439. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  85440. var result = new SceneOptimizerOptions(targetFrameRate);
  85441. var priority = 0;
  85442. result.addOptimization(new MergeMeshesOptimization(priority));
  85443. result.addOptimization(new ShadowsOptimization(priority));
  85444. result.addOptimization(new LensFlaresOptimization(priority));
  85445. // Next priority
  85446. priority++;
  85447. result.addOptimization(new PostProcessesOptimization(priority));
  85448. result.addOptimization(new ParticlesOptimization(priority));
  85449. // Next priority
  85450. priority++;
  85451. result.addOptimization(new TextureOptimization(priority, 1024));
  85452. return result;
  85453. };
  85454. /**
  85455. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  85456. * @param targetFrameRate defines the target frame rate (60 by default)
  85457. * @returns a SceneOptimizerOptions object
  85458. */
  85459. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  85460. var result = new SceneOptimizerOptions(targetFrameRate);
  85461. var priority = 0;
  85462. result.addOptimization(new MergeMeshesOptimization(priority));
  85463. result.addOptimization(new ShadowsOptimization(priority));
  85464. result.addOptimization(new LensFlaresOptimization(priority));
  85465. // Next priority
  85466. priority++;
  85467. result.addOptimization(new PostProcessesOptimization(priority));
  85468. result.addOptimization(new ParticlesOptimization(priority));
  85469. // Next priority
  85470. priority++;
  85471. result.addOptimization(new TextureOptimization(priority, 512));
  85472. // Next priority
  85473. priority++;
  85474. result.addOptimization(new RenderTargetsOptimization(priority));
  85475. // Next priority
  85476. priority++;
  85477. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  85478. return result;
  85479. };
  85480. /**
  85481. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  85482. * @param targetFrameRate defines the target frame rate (60 by default)
  85483. * @returns a SceneOptimizerOptions object
  85484. */
  85485. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  85486. var result = new SceneOptimizerOptions(targetFrameRate);
  85487. var priority = 0;
  85488. result.addOptimization(new MergeMeshesOptimization(priority));
  85489. result.addOptimization(new ShadowsOptimization(priority));
  85490. result.addOptimization(new LensFlaresOptimization(priority));
  85491. // Next priority
  85492. priority++;
  85493. result.addOptimization(new PostProcessesOptimization(priority));
  85494. result.addOptimization(new ParticlesOptimization(priority));
  85495. // Next priority
  85496. priority++;
  85497. result.addOptimization(new TextureOptimization(priority, 256));
  85498. // Next priority
  85499. priority++;
  85500. result.addOptimization(new RenderTargetsOptimization(priority));
  85501. // Next priority
  85502. priority++;
  85503. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  85504. return result;
  85505. };
  85506. return SceneOptimizerOptions;
  85507. }());
  85508. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  85509. /**
  85510. * Class used to run optimizations in order to reach a target frame rate
  85511. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85512. */
  85513. var SceneOptimizer = /** @class */ (function () {
  85514. /**
  85515. * Creates a new SceneOptimizer
  85516. * @param scene defines the scene to work on
  85517. * @param options defines the options to use with the SceneOptimizer
  85518. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  85519. * @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)
  85520. */
  85521. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  85522. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  85523. if (improvementMode === void 0) { improvementMode = false; }
  85524. var _this = this;
  85525. this._isRunning = false;
  85526. this._currentPriorityLevel = 0;
  85527. this._targetFrameRate = 60;
  85528. this._trackerDuration = 2000;
  85529. this._currentFrameRate = 0;
  85530. this._improvementMode = false;
  85531. /**
  85532. * Defines an observable called when the optimizer reaches the target frame rate
  85533. */
  85534. this.onSuccessObservable = new BABYLON.Observable();
  85535. /**
  85536. * Defines an observable called when the optimizer enables an optimization
  85537. */
  85538. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  85539. /**
  85540. * Defines an observable called when the optimizer is not able to reach the target frame rate
  85541. */
  85542. this.onFailureObservable = new BABYLON.Observable();
  85543. if (!options) {
  85544. this._options = new SceneOptimizerOptions();
  85545. }
  85546. else {
  85547. this._options = options;
  85548. }
  85549. if (this._options.targetFrameRate) {
  85550. this._targetFrameRate = this._options.targetFrameRate;
  85551. }
  85552. if (this._options.trackerDuration) {
  85553. this._trackerDuration = this._options.trackerDuration;
  85554. }
  85555. if (autoGeneratePriorities) {
  85556. var priority = 0;
  85557. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  85558. var optim = _a[_i];
  85559. optim.priority = priority++;
  85560. }
  85561. }
  85562. this._improvementMode = improvementMode;
  85563. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85564. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  85565. _this._sceneDisposeObserver = null;
  85566. _this.dispose();
  85567. });
  85568. }
  85569. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  85570. /**
  85571. * Gets a boolean indicating if the optimizer is in improvement mode
  85572. */
  85573. get: function () {
  85574. return this._improvementMode;
  85575. },
  85576. enumerable: true,
  85577. configurable: true
  85578. });
  85579. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  85580. /**
  85581. * Gets the current priority level (0 at start)
  85582. */
  85583. get: function () {
  85584. return this._currentPriorityLevel;
  85585. },
  85586. enumerable: true,
  85587. configurable: true
  85588. });
  85589. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  85590. /**
  85591. * Gets the current frame rate checked by the SceneOptimizer
  85592. */
  85593. get: function () {
  85594. return this._currentFrameRate;
  85595. },
  85596. enumerable: true,
  85597. configurable: true
  85598. });
  85599. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  85600. /**
  85601. * Gets or sets the current target frame rate (60 by default)
  85602. */
  85603. get: function () {
  85604. return this._targetFrameRate;
  85605. },
  85606. /**
  85607. * Gets or sets the current target frame rate (60 by default)
  85608. */
  85609. set: function (value) {
  85610. this._targetFrameRate = value;
  85611. },
  85612. enumerable: true,
  85613. configurable: true
  85614. });
  85615. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  85616. /**
  85617. * Gets or sets the current interval between two checks (every 2000ms by default)
  85618. */
  85619. get: function () {
  85620. return this._trackerDuration;
  85621. },
  85622. /**
  85623. * Gets or sets the current interval between two checks (every 2000ms by default)
  85624. */
  85625. set: function (value) {
  85626. this._trackerDuration = value;
  85627. },
  85628. enumerable: true,
  85629. configurable: true
  85630. });
  85631. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  85632. /**
  85633. * Gets the list of active optimizations
  85634. */
  85635. get: function () {
  85636. return this._options.optimizations;
  85637. },
  85638. enumerable: true,
  85639. configurable: true
  85640. });
  85641. /**
  85642. * Stops the current optimizer
  85643. */
  85644. SceneOptimizer.prototype.stop = function () {
  85645. this._isRunning = false;
  85646. };
  85647. /**
  85648. * Reset the optimizer to initial step (current priority level = 0)
  85649. */
  85650. SceneOptimizer.prototype.reset = function () {
  85651. this._currentPriorityLevel = 0;
  85652. };
  85653. /**
  85654. * Start the optimizer. By default it will try to reach a specific framerate
  85655. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  85656. */
  85657. SceneOptimizer.prototype.start = function () {
  85658. var _this = this;
  85659. if (this._isRunning) {
  85660. return;
  85661. }
  85662. this._isRunning = true;
  85663. // Let's wait for the scene to be ready before running our check
  85664. this._scene.executeWhenReady(function () {
  85665. setTimeout(function () {
  85666. _this._checkCurrentState();
  85667. }, _this._trackerDuration);
  85668. });
  85669. };
  85670. SceneOptimizer.prototype._checkCurrentState = function () {
  85671. var _this = this;
  85672. if (!this._isRunning) {
  85673. return;
  85674. }
  85675. var scene = this._scene;
  85676. var options = this._options;
  85677. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  85678. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  85679. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  85680. this._isRunning = false;
  85681. this.onSuccessObservable.notifyObservers(this);
  85682. return;
  85683. }
  85684. // Apply current level of optimizations
  85685. var allDone = true;
  85686. var noOptimizationApplied = true;
  85687. for (var index = 0; index < options.optimizations.length; index++) {
  85688. var optimization = options.optimizations[index];
  85689. if (optimization.priority === this._currentPriorityLevel) {
  85690. noOptimizationApplied = false;
  85691. allDone = allDone && optimization.apply(scene, this);
  85692. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  85693. }
  85694. }
  85695. // If no optimization was applied, this is a failure :(
  85696. if (noOptimizationApplied) {
  85697. this._isRunning = false;
  85698. this.onFailureObservable.notifyObservers(this);
  85699. return;
  85700. }
  85701. // If all optimizations were done, move to next level
  85702. if (allDone) {
  85703. this._currentPriorityLevel++;
  85704. }
  85705. // Let's the system running for a specific amount of time before checking FPS
  85706. scene.executeWhenReady(function () {
  85707. setTimeout(function () {
  85708. _this._checkCurrentState();
  85709. }, _this._trackerDuration);
  85710. });
  85711. };
  85712. /**
  85713. * Release all resources
  85714. */
  85715. SceneOptimizer.prototype.dispose = function () {
  85716. this.stop();
  85717. this.onSuccessObservable.clear();
  85718. this.onFailureObservable.clear();
  85719. this.onNewOptimizationAppliedObservable.clear();
  85720. if (this._sceneDisposeObserver) {
  85721. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  85722. }
  85723. };
  85724. /**
  85725. * Helper function to create a SceneOptimizer with one single line of code
  85726. * @param scene defines the scene to work on
  85727. * @param options defines the options to use with the SceneOptimizer
  85728. * @param onSuccess defines a callback to call on success
  85729. * @param onFailure defines a callback to call on failure
  85730. * @returns the new SceneOptimizer object
  85731. */
  85732. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  85733. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  85734. if (onSuccess) {
  85735. optimizer.onSuccessObservable.add(function () {
  85736. onSuccess();
  85737. });
  85738. }
  85739. if (onFailure) {
  85740. optimizer.onFailureObservable.add(function () {
  85741. onFailure();
  85742. });
  85743. }
  85744. optimizer.start();
  85745. return optimizer;
  85746. };
  85747. return SceneOptimizer;
  85748. }());
  85749. BABYLON.SceneOptimizer = SceneOptimizer;
  85750. })(BABYLON || (BABYLON = {}));
  85751. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  85752. "use strict";
  85753. var BABYLON;
  85754. (function (BABYLON) {
  85755. var OutlineRenderer = /** @class */ (function () {
  85756. function OutlineRenderer(scene) {
  85757. this.zOffset = 1;
  85758. this._scene = scene;
  85759. }
  85760. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  85761. var _this = this;
  85762. if (useOverlay === void 0) { useOverlay = false; }
  85763. var scene = this._scene;
  85764. var engine = this._scene.getEngine();
  85765. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85766. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  85767. return;
  85768. }
  85769. var mesh = subMesh.getRenderingMesh();
  85770. var material = subMesh.getMaterial();
  85771. if (!material || !scene.activeCamera) {
  85772. return;
  85773. }
  85774. engine.enableEffect(this._effect);
  85775. // Logarithmic depth
  85776. if (material.useLogarithmicDepth) {
  85777. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  85778. }
  85779. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  85780. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  85781. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  85782. // Bones
  85783. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85784. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85785. }
  85786. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  85787. // Alpha test
  85788. if (material && material.needAlphaTesting()) {
  85789. var alphaTexture = material.getAlphaTestTexture();
  85790. if (alphaTexture) {
  85791. this._effect.setTexture("diffuseSampler", alphaTexture);
  85792. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  85793. }
  85794. }
  85795. engine.setZOffset(-this.zOffset);
  85796. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  85797. engine.setZOffset(0);
  85798. };
  85799. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  85800. var defines = [];
  85801. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  85802. var mesh = subMesh.getMesh();
  85803. var material = subMesh.getMaterial();
  85804. if (material) {
  85805. // Alpha test
  85806. if (material.needAlphaTesting()) {
  85807. defines.push("#define ALPHATEST");
  85808. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85809. attribs.push(BABYLON.VertexBuffer.UVKind);
  85810. defines.push("#define UV1");
  85811. }
  85812. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  85813. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85814. defines.push("#define UV2");
  85815. }
  85816. }
  85817. //Logarithmic depth
  85818. if (material.useLogarithmicDepth) {
  85819. defines.push("#define LOGARITHMICDEPTH");
  85820. }
  85821. }
  85822. // Bones
  85823. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85824. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85825. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85826. if (mesh.numBoneInfluencers > 4) {
  85827. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85828. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85829. }
  85830. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85831. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  85832. }
  85833. else {
  85834. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85835. }
  85836. // Instances
  85837. if (useInstances) {
  85838. defines.push("#define INSTANCES");
  85839. attribs.push("world0");
  85840. attribs.push("world1");
  85841. attribs.push("world2");
  85842. attribs.push("world3");
  85843. }
  85844. // Get correct effect
  85845. var join = defines.join("\n");
  85846. if (this._cachedDefines !== join) {
  85847. this._cachedDefines = join;
  85848. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  85849. }
  85850. return this._effect.isReady();
  85851. };
  85852. return OutlineRenderer;
  85853. }());
  85854. BABYLON.OutlineRenderer = OutlineRenderer;
  85855. })(BABYLON || (BABYLON = {}));
  85856. //# sourceMappingURL=babylon.outlineRenderer.js.map
  85857. "use strict";
  85858. var BABYLON;
  85859. (function (BABYLON) {
  85860. var FaceAdjacencies = /** @class */ (function () {
  85861. function FaceAdjacencies() {
  85862. this.edges = new Array();
  85863. this.edgesConnectedCount = 0;
  85864. }
  85865. return FaceAdjacencies;
  85866. }());
  85867. var EdgesRenderer = /** @class */ (function () {
  85868. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  85869. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  85870. if (epsilon === void 0) { epsilon = 0.95; }
  85871. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  85872. this.edgesWidthScalerForOrthographic = 1000.0;
  85873. this.edgesWidthScalerForPerspective = 50.0;
  85874. this._linesPositions = new Array();
  85875. this._linesNormals = new Array();
  85876. this._linesIndices = new Array();
  85877. this._buffers = {};
  85878. this._checkVerticesInsteadOfIndices = false;
  85879. this._source = source;
  85880. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  85881. this._epsilon = epsilon;
  85882. this._prepareRessources();
  85883. this._generateEdgesLines();
  85884. }
  85885. EdgesRenderer.prototype._prepareRessources = function () {
  85886. if (this._lineShader) {
  85887. return;
  85888. }
  85889. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  85890. attributes: ["position", "normal"],
  85891. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  85892. });
  85893. this._lineShader.disableDepthWrite = true;
  85894. this._lineShader.backFaceCulling = false;
  85895. };
  85896. EdgesRenderer.prototype._rebuild = function () {
  85897. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85898. if (buffer) {
  85899. buffer._rebuild();
  85900. }
  85901. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85902. if (buffer) {
  85903. buffer._rebuild();
  85904. }
  85905. var scene = this._source.getScene();
  85906. var engine = scene.getEngine();
  85907. this._ib = engine.createIndexBuffer(this._linesIndices);
  85908. };
  85909. EdgesRenderer.prototype.dispose = function () {
  85910. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85911. if (buffer) {
  85912. buffer.dispose();
  85913. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  85914. }
  85915. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85916. if (buffer) {
  85917. buffer.dispose();
  85918. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  85919. }
  85920. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  85921. this._lineShader.dispose();
  85922. };
  85923. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  85924. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  85925. return 0;
  85926. }
  85927. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  85928. return 1;
  85929. }
  85930. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  85931. return 2;
  85932. }
  85933. return -1;
  85934. };
  85935. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  85936. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  85937. return 0;
  85938. }
  85939. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  85940. return 1;
  85941. }
  85942. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  85943. return 2;
  85944. }
  85945. return -1;
  85946. };
  85947. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  85948. var needToCreateLine;
  85949. if (edge === undefined) {
  85950. needToCreateLine = true;
  85951. }
  85952. else {
  85953. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  85954. needToCreateLine = dotProduct < this._epsilon;
  85955. }
  85956. if (needToCreateLine) {
  85957. var offset = this._linesPositions.length / 3;
  85958. var normal = p0.subtract(p1);
  85959. normal.normalize();
  85960. // Positions
  85961. this._linesPositions.push(p0.x);
  85962. this._linesPositions.push(p0.y);
  85963. this._linesPositions.push(p0.z);
  85964. this._linesPositions.push(p0.x);
  85965. this._linesPositions.push(p0.y);
  85966. this._linesPositions.push(p0.z);
  85967. this._linesPositions.push(p1.x);
  85968. this._linesPositions.push(p1.y);
  85969. this._linesPositions.push(p1.z);
  85970. this._linesPositions.push(p1.x);
  85971. this._linesPositions.push(p1.y);
  85972. this._linesPositions.push(p1.z);
  85973. // Normals
  85974. this._linesNormals.push(p1.x);
  85975. this._linesNormals.push(p1.y);
  85976. this._linesNormals.push(p1.z);
  85977. this._linesNormals.push(-1);
  85978. this._linesNormals.push(p1.x);
  85979. this._linesNormals.push(p1.y);
  85980. this._linesNormals.push(p1.z);
  85981. this._linesNormals.push(1);
  85982. this._linesNormals.push(p0.x);
  85983. this._linesNormals.push(p0.y);
  85984. this._linesNormals.push(p0.z);
  85985. this._linesNormals.push(-1);
  85986. this._linesNormals.push(p0.x);
  85987. this._linesNormals.push(p0.y);
  85988. this._linesNormals.push(p0.z);
  85989. this._linesNormals.push(1);
  85990. // Indices
  85991. this._linesIndices.push(offset);
  85992. this._linesIndices.push(offset + 1);
  85993. this._linesIndices.push(offset + 2);
  85994. this._linesIndices.push(offset);
  85995. this._linesIndices.push(offset + 2);
  85996. this._linesIndices.push(offset + 3);
  85997. }
  85998. };
  85999. EdgesRenderer.prototype._generateEdgesLines = function () {
  86000. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  86001. var indices = this._source.getIndices();
  86002. if (!indices || !positions) {
  86003. return;
  86004. }
  86005. // First let's find adjacencies
  86006. var adjacencies = new Array();
  86007. var faceNormals = new Array();
  86008. var index;
  86009. var faceAdjacencies;
  86010. // Prepare faces
  86011. for (index = 0; index < indices.length; index += 3) {
  86012. faceAdjacencies = new FaceAdjacencies();
  86013. var p0Index = indices[index];
  86014. var p1Index = indices[index + 1];
  86015. var p2Index = indices[index + 2];
  86016. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  86017. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  86018. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  86019. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  86020. faceNormal.normalize();
  86021. faceNormals.push(faceNormal);
  86022. adjacencies.push(faceAdjacencies);
  86023. }
  86024. // Scan
  86025. for (index = 0; index < adjacencies.length; index++) {
  86026. faceAdjacencies = adjacencies[index];
  86027. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  86028. var otherFaceAdjacencies = adjacencies[otherIndex];
  86029. if (faceAdjacencies.edgesConnectedCount === 3) {
  86030. break;
  86031. }
  86032. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  86033. continue;
  86034. }
  86035. var otherP0 = indices[otherIndex * 3];
  86036. var otherP1 = indices[otherIndex * 3 + 1];
  86037. var otherP2 = indices[otherIndex * 3 + 2];
  86038. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  86039. var otherEdgeIndex = 0;
  86040. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  86041. continue;
  86042. }
  86043. switch (edgeIndex) {
  86044. case 0:
  86045. if (this._checkVerticesInsteadOfIndices) {
  86046. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86047. }
  86048. else {
  86049. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  86050. }
  86051. break;
  86052. case 1:
  86053. if (this._checkVerticesInsteadOfIndices) {
  86054. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86055. }
  86056. else {
  86057. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  86058. }
  86059. break;
  86060. case 2:
  86061. if (this._checkVerticesInsteadOfIndices) {
  86062. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86063. }
  86064. else {
  86065. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  86066. }
  86067. break;
  86068. }
  86069. if (otherEdgeIndex === -1) {
  86070. continue;
  86071. }
  86072. faceAdjacencies.edges[edgeIndex] = otherIndex;
  86073. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  86074. faceAdjacencies.edgesConnectedCount++;
  86075. otherFaceAdjacencies.edgesConnectedCount++;
  86076. if (faceAdjacencies.edgesConnectedCount === 3) {
  86077. break;
  86078. }
  86079. }
  86080. }
  86081. }
  86082. // Create lines
  86083. for (index = 0; index < adjacencies.length; index++) {
  86084. // 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
  86085. var current = adjacencies[index];
  86086. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  86087. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  86088. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  86089. }
  86090. // Merge into a single mesh
  86091. var engine = this._source.getScene().getEngine();
  86092. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  86093. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  86094. this._ib = engine.createIndexBuffer(this._linesIndices);
  86095. this._indicesCount = this._linesIndices.length;
  86096. };
  86097. EdgesRenderer.prototype.render = function () {
  86098. var scene = this._source.getScene();
  86099. if (!this._lineShader.isReady() || !scene.activeCamera) {
  86100. return;
  86101. }
  86102. var engine = scene.getEngine();
  86103. this._lineShader._preBind();
  86104. // VBOs
  86105. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  86106. scene.resetCachedMaterial();
  86107. this._lineShader.setColor4("color", this._source.edgesColor);
  86108. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  86109. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  86110. }
  86111. else {
  86112. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  86113. }
  86114. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  86115. this._lineShader.bind(this._source.getWorldMatrix());
  86116. // Draw order
  86117. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  86118. this._lineShader.unbind();
  86119. engine.setDepthWrite(true);
  86120. };
  86121. return EdgesRenderer;
  86122. }());
  86123. BABYLON.EdgesRenderer = EdgesRenderer;
  86124. })(BABYLON || (BABYLON = {}));
  86125. //# sourceMappingURL=babylon.edgesRenderer.js.map
  86126. "use strict";
  86127. var __assign = (this && this.__assign) || Object.assign || function(t) {
  86128. for (var s, i = 1, n = arguments.length; i < n; i++) {
  86129. s = arguments[i];
  86130. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  86131. t[p] = s[p];
  86132. }
  86133. return t;
  86134. };
  86135. var BABYLON;
  86136. (function (BABYLON) {
  86137. /**
  86138. * The effect layer Helps adding post process effect blended with the main pass.
  86139. *
  86140. * This can be for instance use to generate glow or higlight effects on the scene.
  86141. *
  86142. * The effect layer class can not be used directly and is intented to inherited from to be
  86143. * customized per effects.
  86144. */
  86145. var EffectLayer = /** @class */ (function () {
  86146. /**
  86147. * Instantiates a new effect Layer and references it in the scene.
  86148. * @param name The name of the layer
  86149. * @param scene The scene to use the layer in
  86150. */
  86151. function EffectLayer(
  86152. /** The Friendly of the effect in the scene */
  86153. name, scene) {
  86154. this.name = name;
  86155. this._vertexBuffers = {};
  86156. this._maxSize = 0;
  86157. this._mainTextureDesiredSize = { width: 0, height: 0 };
  86158. this._shouldRender = true;
  86159. this._postProcesses = [];
  86160. this._textures = [];
  86161. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  86162. /**
  86163. * The clear color of the texture used to generate the glow map.
  86164. */
  86165. this.neutralColor = new BABYLON.Color4();
  86166. /**
  86167. * Specifies wether the highlight layer is enabled or not.
  86168. */
  86169. this.isEnabled = true;
  86170. /**
  86171. * An event triggered when the effect layer has been disposed.
  86172. */
  86173. this.onDisposeObservable = new BABYLON.Observable();
  86174. /**
  86175. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  86176. */
  86177. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  86178. /**
  86179. * An event triggered when the generated texture is being merged in the scene.
  86180. */
  86181. this.onBeforeComposeObservable = new BABYLON.Observable();
  86182. /**
  86183. * An event triggered when the generated texture has been merged in the scene.
  86184. */
  86185. this.onAfterComposeObservable = new BABYLON.Observable();
  86186. /**
  86187. * An event triggered when the efffect layer changes its size.
  86188. */
  86189. this.onSizeChangedObservable = new BABYLON.Observable();
  86190. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86191. this._engine = scene.getEngine();
  86192. this._maxSize = this._engine.getCaps().maxTextureSize;
  86193. this._scene.effectLayers.push(this);
  86194. // Generate Buffers
  86195. this._generateIndexBuffer();
  86196. this._genrateVertexBuffer();
  86197. }
  86198. Object.defineProperty(EffectLayer.prototype, "camera", {
  86199. /**
  86200. * Gets the camera attached to the layer.
  86201. */
  86202. get: function () {
  86203. return this._effectLayerOptions.camera;
  86204. },
  86205. enumerable: true,
  86206. configurable: true
  86207. });
  86208. /**
  86209. * Initializes the effect layer with the required options.
  86210. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  86211. */
  86212. EffectLayer.prototype._init = function (options) {
  86213. // Adapt options
  86214. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86215. this._setMainTextureSize();
  86216. this._createMainTexture();
  86217. this._createTextureAndPostProcesses();
  86218. this._mergeEffect = this._createMergeEffect();
  86219. };
  86220. /**
  86221. * Generates the index buffer of the full screen quad blending to the main canvas.
  86222. */
  86223. EffectLayer.prototype._generateIndexBuffer = function () {
  86224. // Indices
  86225. var indices = [];
  86226. indices.push(0);
  86227. indices.push(1);
  86228. indices.push(2);
  86229. indices.push(0);
  86230. indices.push(2);
  86231. indices.push(3);
  86232. this._indexBuffer = this._engine.createIndexBuffer(indices);
  86233. };
  86234. /**
  86235. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  86236. */
  86237. EffectLayer.prototype._genrateVertexBuffer = function () {
  86238. // VBO
  86239. var vertices = [];
  86240. vertices.push(1, 1);
  86241. vertices.push(-1, 1);
  86242. vertices.push(-1, -1);
  86243. vertices.push(1, -1);
  86244. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86245. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86246. };
  86247. /**
  86248. * Sets the main texture desired size which is the closest power of two
  86249. * of the engine canvas size.
  86250. */
  86251. EffectLayer.prototype._setMainTextureSize = function () {
  86252. if (this._effectLayerOptions.mainTextureFixedSize) {
  86253. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  86254. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  86255. }
  86256. else {
  86257. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  86258. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  86259. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  86260. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  86261. }
  86262. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  86263. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  86264. };
  86265. /**
  86266. * Creates the main texture for the effect layer.
  86267. */
  86268. EffectLayer.prototype._createMainTexture = function () {
  86269. var _this = this;
  86270. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  86271. width: this._mainTextureDesiredSize.width,
  86272. height: this._mainTextureDesiredSize.height
  86273. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86274. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  86275. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86276. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86277. this._mainTexture.anisotropicFilteringLevel = 1;
  86278. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86279. this._mainTexture.renderParticles = false;
  86280. this._mainTexture.renderList = null;
  86281. this._mainTexture.ignoreCameraViewport = true;
  86282. // Custom render function
  86283. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  86284. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  86285. var index;
  86286. var engine = _this._scene.getEngine();
  86287. if (depthOnlySubMeshes.length) {
  86288. engine.setColorWrite(false);
  86289. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  86290. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  86291. }
  86292. engine.setColorWrite(true);
  86293. }
  86294. for (index = 0; index < opaqueSubMeshes.length; index++) {
  86295. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  86296. }
  86297. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  86298. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  86299. }
  86300. for (index = 0; index < transparentSubMeshes.length; index++) {
  86301. _this._renderSubMesh(transparentSubMeshes.data[index]);
  86302. }
  86303. };
  86304. this._mainTexture.onClearObservable.add(function (engine) {
  86305. engine.clear(_this.neutralColor, true, true, true);
  86306. });
  86307. };
  86308. /**
  86309. * Checks for the readiness of the element composing the layer.
  86310. * @param subMesh the mesh to check for
  86311. * @param useInstances specify wether or not to use instances to render the mesh
  86312. * @param emissiveTexture the associated emissive texture used to generate the glow
  86313. * @return true if ready otherwise, false
  86314. */
  86315. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  86316. var material = subMesh.getMaterial();
  86317. if (!material) {
  86318. return false;
  86319. }
  86320. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  86321. return false;
  86322. }
  86323. var defines = [];
  86324. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86325. var mesh = subMesh.getMesh();
  86326. var uv1 = false;
  86327. var uv2 = false;
  86328. // Alpha test
  86329. if (material && material.needAlphaTesting()) {
  86330. var alphaTexture = material.getAlphaTestTexture();
  86331. if (alphaTexture) {
  86332. defines.push("#define ALPHATEST");
  86333. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86334. alphaTexture.coordinatesIndex === 1) {
  86335. defines.push("#define DIFFUSEUV2");
  86336. uv2 = true;
  86337. }
  86338. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86339. defines.push("#define DIFFUSEUV1");
  86340. uv1 = true;
  86341. }
  86342. }
  86343. }
  86344. // Emissive
  86345. if (emissiveTexture) {
  86346. defines.push("#define EMISSIVE");
  86347. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86348. emissiveTexture.coordinatesIndex === 1) {
  86349. defines.push("#define EMISSIVEUV2");
  86350. uv2 = true;
  86351. }
  86352. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86353. defines.push("#define EMISSIVEUV1");
  86354. uv1 = true;
  86355. }
  86356. }
  86357. if (uv1) {
  86358. attribs.push(BABYLON.VertexBuffer.UVKind);
  86359. defines.push("#define UV1");
  86360. }
  86361. if (uv2) {
  86362. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86363. defines.push("#define UV2");
  86364. }
  86365. // Bones
  86366. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86367. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86368. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86369. if (mesh.numBoneInfluencers > 4) {
  86370. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86371. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86372. }
  86373. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86374. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  86375. }
  86376. else {
  86377. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86378. }
  86379. // Instances
  86380. if (useInstances) {
  86381. defines.push("#define INSTANCES");
  86382. attribs.push("world0");
  86383. attribs.push("world1");
  86384. attribs.push("world2");
  86385. attribs.push("world3");
  86386. }
  86387. // Get correct effect
  86388. var join = defines.join("\n");
  86389. if (this._cachedDefines !== join) {
  86390. this._cachedDefines = join;
  86391. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  86392. }
  86393. return this._effectLayerMapGenerationEffect.isReady();
  86394. };
  86395. /**
  86396. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  86397. */
  86398. EffectLayer.prototype.render = function () {
  86399. var currentEffect = this._mergeEffect;
  86400. // Check
  86401. if (!currentEffect.isReady())
  86402. return;
  86403. for (var i = 0; i < this._postProcesses.length; i++) {
  86404. if (!this._postProcesses[i].isReady()) {
  86405. return;
  86406. }
  86407. }
  86408. var engine = this._scene.getEngine();
  86409. this.onBeforeComposeObservable.notifyObservers(this);
  86410. // Render
  86411. engine.enableEffect(currentEffect);
  86412. engine.setState(false);
  86413. // VBOs
  86414. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86415. // Cache
  86416. var previousAlphaMode = engine.getAlphaMode();
  86417. // Go Blend.
  86418. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  86419. // Blends the map on the main canvas.
  86420. this._internalRender(currentEffect);
  86421. // Restore Alpha
  86422. engine.setAlphaMode(previousAlphaMode);
  86423. this.onAfterComposeObservable.notifyObservers(this);
  86424. // Handle size changes.
  86425. var size = this._mainTexture.getSize();
  86426. this._setMainTextureSize();
  86427. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  86428. // Recreate RTT and post processes on size change.
  86429. this.onSizeChangedObservable.notifyObservers(this);
  86430. this._disposeTextureAndPostProcesses();
  86431. this._createMainTexture();
  86432. this._createTextureAndPostProcesses();
  86433. }
  86434. };
  86435. /**
  86436. * Determine if a given mesh will be used in the current effect.
  86437. * @param mesh mesh to test
  86438. * @returns true if the mesh will be used
  86439. */
  86440. EffectLayer.prototype.hasMesh = function (mesh) {
  86441. return true;
  86442. };
  86443. /**
  86444. * Returns true if the layer contains information to display, otherwise false.
  86445. * @returns true if the glow layer should be rendered
  86446. */
  86447. EffectLayer.prototype.shouldRender = function () {
  86448. return this.isEnabled && this._shouldRender;
  86449. };
  86450. /**
  86451. * Returns true if the mesh should render, otherwise false.
  86452. * @param mesh The mesh to render
  86453. * @returns true if it should render otherwise false
  86454. */
  86455. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  86456. return true;
  86457. };
  86458. /**
  86459. * Returns true if the mesh should render, otherwise false.
  86460. * @param mesh The mesh to render
  86461. * @returns true if it should render otherwise false
  86462. */
  86463. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  86464. return true;
  86465. };
  86466. /**
  86467. * Renders the submesh passed in parameter to the generation map.
  86468. */
  86469. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  86470. var _this = this;
  86471. if (!this.shouldRender()) {
  86472. return;
  86473. }
  86474. var material = subMesh.getMaterial();
  86475. var mesh = subMesh.getRenderingMesh();
  86476. var scene = this._scene;
  86477. var engine = scene.getEngine();
  86478. if (!material) {
  86479. return;
  86480. }
  86481. // Do not block in blend mode.
  86482. if (material.needAlphaBlendingForMesh(mesh)) {
  86483. return;
  86484. }
  86485. // Culling
  86486. engine.setState(material.backFaceCulling);
  86487. // Managing instances
  86488. var batch = mesh._getInstancesRenderList(subMesh._id);
  86489. if (batch.mustReturn) {
  86490. return;
  86491. }
  86492. // Early Exit per mesh
  86493. if (!this._shouldRenderMesh(mesh)) {
  86494. return;
  86495. }
  86496. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  86497. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  86498. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  86499. engine.enableEffect(this._effectLayerMapGenerationEffect);
  86500. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  86501. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  86502. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  86503. // Alpha test
  86504. if (material && material.needAlphaTesting()) {
  86505. var alphaTexture = material.getAlphaTestTexture();
  86506. if (alphaTexture) {
  86507. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  86508. var textureMatrix = alphaTexture.getTextureMatrix();
  86509. if (textureMatrix) {
  86510. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  86511. }
  86512. }
  86513. }
  86514. // Glow emissive only
  86515. if (this._emissiveTextureAndColor.texture) {
  86516. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  86517. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  86518. }
  86519. // Bones
  86520. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86521. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86522. }
  86523. // Draw
  86524. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  86525. }
  86526. else {
  86527. // Need to reset refresh rate of the shadowMap
  86528. this._mainTexture.resetRefreshCounter();
  86529. }
  86530. };
  86531. /**
  86532. * Rebuild the required buffers.
  86533. * @ignore Internal use only.
  86534. */
  86535. EffectLayer.prototype._rebuild = function () {
  86536. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86537. if (vb) {
  86538. vb._rebuild();
  86539. }
  86540. this._generateIndexBuffer();
  86541. };
  86542. /**
  86543. * Dispose only the render target textures and post process.
  86544. */
  86545. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  86546. this._mainTexture.dispose();
  86547. for (var i = 0; i < this._postProcesses.length; i++) {
  86548. if (this._postProcesses[i]) {
  86549. this._postProcesses[i].dispose();
  86550. }
  86551. }
  86552. this._postProcesses = [];
  86553. for (var i = 0; i < this._textures.length; i++) {
  86554. if (this._textures[i]) {
  86555. this._textures[i].dispose();
  86556. }
  86557. }
  86558. this._textures = [];
  86559. };
  86560. /**
  86561. * Dispose the highlight layer and free resources.
  86562. */
  86563. EffectLayer.prototype.dispose = function () {
  86564. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86565. if (vertexBuffer) {
  86566. vertexBuffer.dispose();
  86567. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86568. }
  86569. if (this._indexBuffer) {
  86570. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86571. this._indexBuffer = null;
  86572. }
  86573. // Clean textures and post processes
  86574. this._disposeTextureAndPostProcesses();
  86575. // Remove from scene
  86576. var index = this._scene.effectLayers.indexOf(this, 0);
  86577. if (index > -1) {
  86578. this._scene.effectLayers.splice(index, 1);
  86579. }
  86580. // Callback
  86581. this.onDisposeObservable.notifyObservers(this);
  86582. this.onDisposeObservable.clear();
  86583. this.onBeforeRenderMainTextureObservable.clear();
  86584. this.onBeforeComposeObservable.clear();
  86585. this.onAfterComposeObservable.clear();
  86586. this.onSizeChangedObservable.clear();
  86587. };
  86588. return EffectLayer;
  86589. }());
  86590. BABYLON.EffectLayer = EffectLayer;
  86591. })(BABYLON || (BABYLON = {}));
  86592. //# sourceMappingURL=babylon.effectLayer.js.map
  86593. "use strict";
  86594. var BABYLON;
  86595. (function (BABYLON) {
  86596. /**
  86597. * Special Glow Blur post process only blurring the alpha channel
  86598. * It enforces keeping the most luminous color in the color channel.
  86599. */
  86600. var GlowBlurPostProcess = /** @class */ (function (_super) {
  86601. __extends(GlowBlurPostProcess, _super);
  86602. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  86603. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86604. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  86605. _this.direction = direction;
  86606. _this.kernel = kernel;
  86607. _this.onApplyObservable.add(function (effect) {
  86608. effect.setFloat2("screenSize", _this.width, _this.height);
  86609. effect.setVector2("direction", _this.direction);
  86610. effect.setFloat("blurWidth", _this.kernel);
  86611. });
  86612. return _this;
  86613. }
  86614. return GlowBlurPostProcess;
  86615. }(BABYLON.PostProcess));
  86616. /**
  86617. * The highlight layer Helps adding a glow effect around a mesh.
  86618. *
  86619. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86620. * glowy meshes to your scene.
  86621. *
  86622. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  86623. */
  86624. var HighlightLayer = /** @class */ (function (_super) {
  86625. __extends(HighlightLayer, _super);
  86626. /**
  86627. * Instantiates a new highlight Layer and references it to the scene..
  86628. * @param name The name of the layer
  86629. * @param scene The scene to use the layer in
  86630. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  86631. */
  86632. function HighlightLayer(name, scene, options) {
  86633. var _this = _super.call(this, name, scene) || this;
  86634. _this.name = name;
  86635. /**
  86636. * Specifies whether or not the inner glow is ACTIVE in the layer.
  86637. */
  86638. _this.innerGlow = true;
  86639. /**
  86640. * Specifies whether or not the outer glow is ACTIVE in the layer.
  86641. */
  86642. _this.outerGlow = true;
  86643. /**
  86644. * An event triggered when the highlight layer is being blurred.
  86645. */
  86646. _this.onBeforeBlurObservable = new BABYLON.Observable();
  86647. /**
  86648. * An event triggered when the highlight layer has been blurred.
  86649. */
  86650. _this.onAfterBlurObservable = new BABYLON.Observable();
  86651. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  86652. _this._meshes = {};
  86653. _this._excludedMeshes = {};
  86654. _this.neutralColor = HighlightLayer.NeutralColor;
  86655. // Warn on stencil
  86656. if (!_this._engine.isStencilEnable) {
  86657. 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 }");
  86658. }
  86659. // Adapt options
  86660. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86661. // Initialize the layer
  86662. _this._init({
  86663. alphaBlendingMode: _this._options.alphaBlendingMode,
  86664. camera: _this._options.camera,
  86665. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  86666. mainTextureRatio: _this._options.mainTextureRatio
  86667. });
  86668. // Do not render as long as no meshes have been added
  86669. _this._shouldRender = false;
  86670. return _this;
  86671. }
  86672. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  86673. /**
  86674. * Gets the horizontal size of the blur.
  86675. */
  86676. get: function () {
  86677. return this._horizontalBlurPostprocess.kernel;
  86678. },
  86679. /**
  86680. * Specifies the horizontal size of the blur.
  86681. */
  86682. set: function (value) {
  86683. this._horizontalBlurPostprocess.kernel = value;
  86684. },
  86685. enumerable: true,
  86686. configurable: true
  86687. });
  86688. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  86689. /**
  86690. * Gets the vertical size of the blur.
  86691. */
  86692. get: function () {
  86693. return this._verticalBlurPostprocess.kernel;
  86694. },
  86695. /**
  86696. * Specifies the vertical size of the blur.
  86697. */
  86698. set: function (value) {
  86699. this._verticalBlurPostprocess.kernel = value;
  86700. },
  86701. enumerable: true,
  86702. configurable: true
  86703. });
  86704. /**
  86705. * Get the effect name of the layer.
  86706. * @return The effect name
  86707. */
  86708. HighlightLayer.prototype.getEffectName = function () {
  86709. return HighlightLayer.EffectName;
  86710. };
  86711. /**
  86712. * Create the merge effect. This is the shader use to blit the information back
  86713. * to the main canvas at the end of the scene rendering.
  86714. */
  86715. HighlightLayer.prototype._createMergeEffect = function () {
  86716. // Effect
  86717. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  86718. };
  86719. /**
  86720. * Creates the render target textures and post processes used in the highlight layer.
  86721. */
  86722. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  86723. var _this = this;
  86724. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  86725. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  86726. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  86727. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  86728. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  86729. width: blurTextureWidth,
  86730. height: blurTextureHeight
  86731. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86732. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86733. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86734. this._blurTexture.anisotropicFilteringLevel = 16;
  86735. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  86736. this._blurTexture.renderParticles = false;
  86737. this._blurTexture.ignoreCameraViewport = true;
  86738. this._textures = [this._blurTexture];
  86739. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  86740. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86741. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  86742. effect.setTexture("textureSampler", _this._mainTexture);
  86743. });
  86744. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86745. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86746. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86747. });
  86748. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86749. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  86750. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86751. });
  86752. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86753. }
  86754. else {
  86755. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  86756. width: blurTextureWidth,
  86757. height: blurTextureHeight
  86758. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86759. this._horizontalBlurPostprocess.width = blurTextureWidth;
  86760. this._horizontalBlurPostprocess.height = blurTextureHeight;
  86761. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86762. effect.setTexture("textureSampler", _this._mainTexture);
  86763. });
  86764. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  86765. width: blurTextureWidth,
  86766. height: blurTextureHeight
  86767. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86768. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86769. }
  86770. this._mainTexture.onAfterUnbindObservable.add(function () {
  86771. _this.onBeforeBlurObservable.notifyObservers(_this);
  86772. var internalTexture = _this._blurTexture.getInternalTexture();
  86773. if (internalTexture) {
  86774. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  86775. }
  86776. _this.onAfterBlurObservable.notifyObservers(_this);
  86777. });
  86778. // Prevent autoClear.
  86779. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86780. };
  86781. /**
  86782. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86783. */
  86784. HighlightLayer.prototype.needStencil = function () {
  86785. return true;
  86786. };
  86787. /**
  86788. * Checks for the readiness of the element composing the layer.
  86789. * @param subMesh the mesh to check for
  86790. * @param useInstances specify wether or not to use instances to render the mesh
  86791. * @param emissiveTexture the associated emissive texture used to generate the glow
  86792. * @return true if ready otherwise, false
  86793. */
  86794. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  86795. var material = subMesh.getMaterial();
  86796. var mesh = subMesh.getRenderingMesh();
  86797. if (!material || !mesh || !this._meshes) {
  86798. return false;
  86799. }
  86800. var emissiveTexture = null;
  86801. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86802. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86803. emissiveTexture = material.emissiveTexture;
  86804. }
  86805. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86806. };
  86807. /**
  86808. * Implementation specific of rendering the generating effect on the main canvas.
  86809. * @param effect The effect used to render through
  86810. */
  86811. HighlightLayer.prototype._internalRender = function (effect) {
  86812. // Texture
  86813. effect.setTexture("textureSampler", this._blurTexture);
  86814. // Cache
  86815. var engine = this._engine;
  86816. var previousStencilBuffer = engine.getStencilBuffer();
  86817. var previousStencilFunction = engine.getStencilFunction();
  86818. var previousStencilMask = engine.getStencilMask();
  86819. var previousStencilOperationPass = engine.getStencilOperationPass();
  86820. var previousStencilOperationFail = engine.getStencilOperationFail();
  86821. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  86822. var previousStencilReference = engine.getStencilFunctionReference();
  86823. // Stencil operations
  86824. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  86825. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  86826. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  86827. // Draw order
  86828. engine.setStencilMask(0x00);
  86829. engine.setStencilBuffer(true);
  86830. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  86831. // 2 passes inner outer
  86832. if (this.outerGlow) {
  86833. effect.setFloat("offset", 0);
  86834. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  86835. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86836. }
  86837. if (this.innerGlow) {
  86838. effect.setFloat("offset", 1);
  86839. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  86840. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86841. }
  86842. // Restore Cache
  86843. engine.setStencilFunction(previousStencilFunction);
  86844. engine.setStencilMask(previousStencilMask);
  86845. engine.setStencilBuffer(previousStencilBuffer);
  86846. engine.setStencilOperationPass(previousStencilOperationPass);
  86847. engine.setStencilOperationFail(previousStencilOperationFail);
  86848. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  86849. engine.setStencilFunctionReference(previousStencilReference);
  86850. };
  86851. /**
  86852. * Returns true if the layer contains information to display, otherwise false.
  86853. */
  86854. HighlightLayer.prototype.shouldRender = function () {
  86855. if (_super.prototype.shouldRender.call(this)) {
  86856. return this._meshes ? true : false;
  86857. }
  86858. return false;
  86859. };
  86860. /**
  86861. * Returns true if the mesh should render, otherwise false.
  86862. * @param mesh The mesh to render
  86863. * @returns true if it should render otherwise false
  86864. */
  86865. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  86866. // Excluded Mesh
  86867. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  86868. return false;
  86869. }
  86870. ;
  86871. return true;
  86872. };
  86873. /**
  86874. * Sets the required values for both the emissive texture and and the main color.
  86875. */
  86876. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86877. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86878. if (highlightLayerMesh) {
  86879. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  86880. }
  86881. else {
  86882. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86883. }
  86884. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86885. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86886. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  86887. }
  86888. else {
  86889. this._emissiveTextureAndColor.texture = null;
  86890. }
  86891. };
  86892. /**
  86893. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  86894. * @param mesh The mesh to exclude from the highlight layer
  86895. */
  86896. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  86897. if (!this._excludedMeshes) {
  86898. return;
  86899. }
  86900. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86901. if (!meshExcluded) {
  86902. this._excludedMeshes[mesh.uniqueId] = {
  86903. mesh: mesh,
  86904. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  86905. mesh.getEngine().setStencilBuffer(false);
  86906. }),
  86907. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  86908. mesh.getEngine().setStencilBuffer(true);
  86909. }),
  86910. };
  86911. }
  86912. };
  86913. /**
  86914. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  86915. * @param mesh The mesh to highlight
  86916. */
  86917. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  86918. if (!this._excludedMeshes) {
  86919. return;
  86920. }
  86921. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86922. if (meshExcluded) {
  86923. if (meshExcluded.beforeRender) {
  86924. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  86925. }
  86926. if (meshExcluded.afterRender) {
  86927. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  86928. }
  86929. }
  86930. this._excludedMeshes[mesh.uniqueId] = null;
  86931. };
  86932. /**
  86933. * Determine if a given mesh will be highlighted by the current HighlightLayer
  86934. * @param mesh mesh to test
  86935. * @returns true if the mesh will be highlighted by the current HighlightLayer
  86936. */
  86937. HighlightLayer.prototype.hasMesh = function (mesh) {
  86938. if (!this._meshes) {
  86939. return false;
  86940. }
  86941. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  86942. };
  86943. /**
  86944. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  86945. * @param mesh The mesh to highlight
  86946. * @param color The color of the highlight
  86947. * @param glowEmissiveOnly Extract the glow from the emissive texture
  86948. */
  86949. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  86950. var _this = this;
  86951. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  86952. if (!this._meshes) {
  86953. return;
  86954. }
  86955. var meshHighlight = this._meshes[mesh.uniqueId];
  86956. if (meshHighlight) {
  86957. meshHighlight.color = color;
  86958. }
  86959. else {
  86960. this._meshes[mesh.uniqueId] = {
  86961. mesh: mesh,
  86962. color: color,
  86963. // Lambda required for capture due to Observable this context
  86964. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  86965. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  86966. _this._defaultStencilReference(mesh);
  86967. }
  86968. else {
  86969. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  86970. }
  86971. }),
  86972. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  86973. glowEmissiveOnly: glowEmissiveOnly
  86974. };
  86975. }
  86976. this._shouldRender = true;
  86977. };
  86978. /**
  86979. * Remove a mesh from the highlight layer in order to make it stop glowing.
  86980. * @param mesh The mesh to highlight
  86981. */
  86982. HighlightLayer.prototype.removeMesh = function (mesh) {
  86983. if (!this._meshes) {
  86984. return;
  86985. }
  86986. var meshHighlight = this._meshes[mesh.uniqueId];
  86987. if (meshHighlight) {
  86988. if (meshHighlight.observerHighlight) {
  86989. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  86990. }
  86991. if (meshHighlight.observerDefault) {
  86992. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  86993. }
  86994. delete this._meshes[mesh.uniqueId];
  86995. }
  86996. this._shouldRender = false;
  86997. for (var meshHighlightToCheck in this._meshes) {
  86998. if (this._meshes[meshHighlightToCheck]) {
  86999. this._shouldRender = true;
  87000. break;
  87001. }
  87002. }
  87003. };
  87004. /**
  87005. * Force the stencil to the normal expected value for none glowing parts
  87006. */
  87007. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  87008. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  87009. };
  87010. /**
  87011. * Free any resources and references associated to a mesh.
  87012. * Internal use
  87013. * @param mesh The mesh to free.
  87014. */
  87015. HighlightLayer.prototype._disposeMesh = function (mesh) {
  87016. this.removeMesh(mesh);
  87017. this.removeExcludedMesh(mesh);
  87018. };
  87019. /**
  87020. * Dispose the highlight layer and free resources.
  87021. */
  87022. HighlightLayer.prototype.dispose = function () {
  87023. if (this._meshes) {
  87024. // Clean mesh references
  87025. for (var id in this._meshes) {
  87026. var meshHighlight = this._meshes[id];
  87027. if (meshHighlight && meshHighlight.mesh) {
  87028. if (meshHighlight.observerHighlight) {
  87029. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87030. }
  87031. if (meshHighlight.observerDefault) {
  87032. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87033. }
  87034. }
  87035. }
  87036. this._meshes = null;
  87037. }
  87038. if (this._excludedMeshes) {
  87039. for (var id in this._excludedMeshes) {
  87040. var meshHighlight = this._excludedMeshes[id];
  87041. if (meshHighlight) {
  87042. if (meshHighlight.beforeRender) {
  87043. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  87044. }
  87045. if (meshHighlight.afterRender) {
  87046. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  87047. }
  87048. }
  87049. }
  87050. this._excludedMeshes = null;
  87051. }
  87052. _super.prototype.dispose.call(this);
  87053. };
  87054. /**
  87055. * Effect Name of the highlight layer.
  87056. */
  87057. HighlightLayer.EffectName = "HighlightLayer";
  87058. /**
  87059. * The neutral color used during the preparation of the glow effect.
  87060. * This is black by default as the blend operation is a blend operation.
  87061. */
  87062. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  87063. /**
  87064. * Stencil value used for glowing meshes.
  87065. */
  87066. HighlightLayer.GlowingMeshStencilReference = 0x02;
  87067. /**
  87068. * Stencil value used for the other meshes in the scene.
  87069. */
  87070. HighlightLayer.NormalMeshStencilReference = 0x01;
  87071. return HighlightLayer;
  87072. }(BABYLON.EffectLayer));
  87073. BABYLON.HighlightLayer = HighlightLayer;
  87074. })(BABYLON || (BABYLON = {}));
  87075. //# sourceMappingURL=babylon.highlightLayer.js.map
  87076. "use strict";
  87077. var BABYLON;
  87078. (function (BABYLON) {
  87079. /**
  87080. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  87081. *
  87082. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  87083. * glowy meshes to your scene.
  87084. *
  87085. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  87086. */
  87087. var GlowLayer = /** @class */ (function (_super) {
  87088. __extends(GlowLayer, _super);
  87089. /**
  87090. * Instantiates a new glow Layer and references it to the scene.
  87091. * @param name The name of the layer
  87092. * @param scene The scene to use the layer in
  87093. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  87094. */
  87095. function GlowLayer(name, scene, options) {
  87096. var _this = _super.call(this, name, scene) || this;
  87097. _this.name = name;
  87098. _this._intensity = 1.0;
  87099. _this._includedOnlyMeshes = [];
  87100. _this._excludedMeshes = [];
  87101. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  87102. // Adapt options
  87103. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  87104. // Initialize the layer
  87105. _this._init({
  87106. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  87107. camera: _this._options.camera,
  87108. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  87109. mainTextureRatio: _this._options.mainTextureRatio
  87110. });
  87111. return _this;
  87112. }
  87113. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  87114. /**
  87115. * Gets the kernel size of the blur.
  87116. */
  87117. get: function () {
  87118. return this._horizontalBlurPostprocess1.kernel;
  87119. },
  87120. /**
  87121. * Sets the kernel size of the blur.
  87122. */
  87123. set: function (value) {
  87124. this._horizontalBlurPostprocess1.kernel = value;
  87125. this._verticalBlurPostprocess1.kernel = value;
  87126. this._horizontalBlurPostprocess2.kernel = value;
  87127. this._verticalBlurPostprocess2.kernel = value;
  87128. },
  87129. enumerable: true,
  87130. configurable: true
  87131. });
  87132. Object.defineProperty(GlowLayer.prototype, "intensity", {
  87133. /**
  87134. * Gets the glow intensity.
  87135. */
  87136. get: function () {
  87137. return this._intensity;
  87138. },
  87139. /**
  87140. * Sets the glow intensity.
  87141. */
  87142. set: function (value) {
  87143. this._intensity = value;
  87144. },
  87145. enumerable: true,
  87146. configurable: true
  87147. });
  87148. /**
  87149. * Get the effect name of the layer.
  87150. * @return The effect name
  87151. */
  87152. GlowLayer.prototype.getEffectName = function () {
  87153. return GlowLayer.EffectName;
  87154. };
  87155. /**
  87156. * Create the merge effect. This is the shader use to blit the information back
  87157. * to the main canvas at the end of the scene rendering.
  87158. */
  87159. GlowLayer.prototype._createMergeEffect = function () {
  87160. // Effect
  87161. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  87162. };
  87163. /**
  87164. * Creates the render target textures and post processes used in the glow layer.
  87165. */
  87166. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  87167. var _this = this;
  87168. var blurTextureWidth = this._mainTextureDesiredSize.width;
  87169. var blurTextureHeight = this._mainTextureDesiredSize.height;
  87170. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  87171. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  87172. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  87173. width: blurTextureWidth,
  87174. height: blurTextureHeight
  87175. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87176. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87177. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87178. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87179. this._blurTexture1.renderParticles = false;
  87180. this._blurTexture1.ignoreCameraViewport = true;
  87181. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  87182. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  87183. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  87184. width: blurTextureWidth2,
  87185. height: blurTextureHeight2
  87186. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87187. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87188. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87189. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87190. this._blurTexture2.renderParticles = false;
  87191. this._blurTexture2.ignoreCameraViewport = true;
  87192. this._textures = [this._blurTexture1, this._blurTexture2];
  87193. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87194. width: blurTextureWidth,
  87195. height: blurTextureHeight
  87196. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87197. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  87198. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  87199. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  87200. effect.setTexture("textureSampler", _this._mainTexture);
  87201. });
  87202. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87203. width: blurTextureWidth,
  87204. height: blurTextureHeight
  87205. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87206. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87207. width: blurTextureWidth2,
  87208. height: blurTextureHeight2
  87209. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87210. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  87211. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  87212. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  87213. effect.setTexture("textureSampler", _this._blurTexture1);
  87214. });
  87215. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87216. width: blurTextureWidth2,
  87217. height: blurTextureHeight2
  87218. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87219. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87220. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  87221. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87222. this._mainTexture.samples = this._options.mainTextureSamples;
  87223. this._mainTexture.onAfterUnbindObservable.add(function () {
  87224. var internalTexture = _this._blurTexture1.getInternalTexture();
  87225. if (internalTexture) {
  87226. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  87227. internalTexture = _this._blurTexture2.getInternalTexture();
  87228. if (internalTexture) {
  87229. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  87230. }
  87231. }
  87232. });
  87233. // Prevent autoClear.
  87234. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  87235. };
  87236. /**
  87237. * Checks for the readiness of the element composing the layer.
  87238. * @param subMesh the mesh to check for
  87239. * @param useInstances specify wether or not to use instances to render the mesh
  87240. * @param emissiveTexture the associated emissive texture used to generate the glow
  87241. * @return true if ready otherwise, false
  87242. */
  87243. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  87244. var material = subMesh.getMaterial();
  87245. var mesh = subMesh.getRenderingMesh();
  87246. if (!material || !mesh) {
  87247. return false;
  87248. }
  87249. var emissiveTexture = material.emissiveTexture;
  87250. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  87251. };
  87252. /**
  87253. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  87254. */
  87255. GlowLayer.prototype.needStencil = function () {
  87256. return false;
  87257. };
  87258. /**
  87259. * Implementation specific of rendering the generating effect on the main canvas.
  87260. * @param effect The effect used to render through
  87261. */
  87262. GlowLayer.prototype._internalRender = function (effect) {
  87263. // Texture
  87264. effect.setTexture("textureSampler", this._blurTexture1);
  87265. effect.setTexture("textureSampler2", this._blurTexture2);
  87266. effect.setFloat("offset", this._intensity);
  87267. // Cache
  87268. var engine = this._engine;
  87269. var previousStencilBuffer = engine.getStencilBuffer();
  87270. // Draw order
  87271. engine.setStencilBuffer(false);
  87272. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87273. // Draw order
  87274. engine.setStencilBuffer(previousStencilBuffer);
  87275. };
  87276. /**
  87277. * Sets the required values for both the emissive texture and and the main color.
  87278. */
  87279. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87280. var textureLevel = 1.0;
  87281. if (this.customEmissiveTextureSelector) {
  87282. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  87283. }
  87284. else {
  87285. if (material) {
  87286. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87287. if (this._emissiveTextureAndColor.texture) {
  87288. textureLevel = this._emissiveTextureAndColor.texture.level;
  87289. }
  87290. }
  87291. else {
  87292. this._emissiveTextureAndColor.texture = null;
  87293. }
  87294. }
  87295. if (this.customEmissiveColorSelector) {
  87296. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  87297. }
  87298. else {
  87299. if (material.emissiveColor) {
  87300. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  87301. }
  87302. else {
  87303. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87304. }
  87305. }
  87306. };
  87307. /**
  87308. * Returns true if the mesh should render, otherwise false.
  87309. * @param mesh The mesh to render
  87310. * @returns true if it should render otherwise false
  87311. */
  87312. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  87313. return this.hasMesh(mesh);
  87314. };
  87315. /**
  87316. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  87317. * @param mesh The mesh to exclude from the glow layer
  87318. */
  87319. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  87320. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  87321. this._excludedMeshes.push(mesh.uniqueId);
  87322. }
  87323. };
  87324. /**
  87325. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  87326. * @param mesh The mesh to remove
  87327. */
  87328. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  87329. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  87330. if (index !== -1) {
  87331. this._excludedMeshes.splice(index, 1);
  87332. }
  87333. };
  87334. /**
  87335. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  87336. * @param mesh The mesh to include in the glow layer
  87337. */
  87338. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  87339. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  87340. this._includedOnlyMeshes.push(mesh.uniqueId);
  87341. }
  87342. };
  87343. /**
  87344. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  87345. * @param mesh The mesh to remove
  87346. */
  87347. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  87348. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  87349. if (index !== -1) {
  87350. this._includedOnlyMeshes.splice(index, 1);
  87351. }
  87352. };
  87353. /**
  87354. * Determine if a given mesh will be used in the glow layer
  87355. * @param mesh The mesh to test
  87356. * @returns true if the mesh will be highlighted by the current glow layer
  87357. */
  87358. GlowLayer.prototype.hasMesh = function (mesh) {
  87359. // Included Mesh
  87360. if (this._includedOnlyMeshes.length) {
  87361. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  87362. }
  87363. ;
  87364. // Excluded Mesh
  87365. if (this._excludedMeshes.length) {
  87366. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  87367. }
  87368. ;
  87369. return true;
  87370. };
  87371. /**
  87372. * Free any resources and references associated to a mesh.
  87373. * Internal use
  87374. * @param mesh The mesh to free.
  87375. */
  87376. GlowLayer.prototype._disposeMesh = function (mesh) {
  87377. this.removeIncludedOnlyMesh(mesh);
  87378. this.removeExcludedMesh(mesh);
  87379. };
  87380. /**
  87381. * Effect Name of the layer.
  87382. */
  87383. GlowLayer.EffectName = "GlowLayer";
  87384. /**
  87385. * The default blur kernel size used for the glow.
  87386. */
  87387. GlowLayer.DefaultBlurKernelSize = 32;
  87388. /**
  87389. * The default texture size ratio used for the glow.
  87390. */
  87391. GlowLayer.DefaultTextureRatio = 0.5;
  87392. return GlowLayer;
  87393. }(BABYLON.EffectLayer));
  87394. BABYLON.GlowLayer = GlowLayer;
  87395. })(BABYLON || (BABYLON = {}));
  87396. //# sourceMappingURL=babylon.glowLayer.js.map
  87397. "use strict";
  87398. var BABYLON;
  87399. (function (BABYLON) {
  87400. /**
  87401. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  87402. */
  87403. var AssetTaskState;
  87404. (function (AssetTaskState) {
  87405. /**
  87406. * Initialization
  87407. */
  87408. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  87409. /**
  87410. * Running
  87411. */
  87412. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  87413. /**
  87414. * Done
  87415. */
  87416. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  87417. /**
  87418. * Error
  87419. */
  87420. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  87421. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  87422. /**
  87423. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  87424. */
  87425. var AbstractAssetTask = /** @class */ (function () {
  87426. /**
  87427. * Creates a new {BABYLON.AssetsManager}
  87428. * @param name defines the name of the task
  87429. */
  87430. function AbstractAssetTask(
  87431. /**
  87432. * Task name
  87433. */ name) {
  87434. this.name = name;
  87435. this._isCompleted = false;
  87436. this._taskState = AssetTaskState.INIT;
  87437. }
  87438. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  87439. /**
  87440. * Get if the task is completed
  87441. */
  87442. get: function () {
  87443. return this._isCompleted;
  87444. },
  87445. enumerable: true,
  87446. configurable: true
  87447. });
  87448. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  87449. /**
  87450. * Gets the current state of the task
  87451. */
  87452. get: function () {
  87453. return this._taskState;
  87454. },
  87455. enumerable: true,
  87456. configurable: true
  87457. });
  87458. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  87459. /**
  87460. * Gets the current error object (if task is in error)
  87461. */
  87462. get: function () {
  87463. return this._errorObject;
  87464. },
  87465. enumerable: true,
  87466. configurable: true
  87467. });
  87468. /**
  87469. * Internal only
  87470. * @ignore
  87471. */
  87472. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  87473. if (this._errorObject) {
  87474. return;
  87475. }
  87476. this._errorObject = {
  87477. message: message,
  87478. exception: exception
  87479. };
  87480. };
  87481. /**
  87482. * Execute the current task
  87483. * @param scene defines the scene where you want your assets to be loaded
  87484. * @param onSuccess is a callback called when the task is successfully executed
  87485. * @param onError is a callback called if an error occurs
  87486. */
  87487. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87488. var _this = this;
  87489. this._taskState = AssetTaskState.RUNNING;
  87490. this.runTask(scene, function () {
  87491. _this.onDoneCallback(onSuccess, onError);
  87492. }, function (msg, exception) {
  87493. _this.onErrorCallback(onError, msg, exception);
  87494. });
  87495. };
  87496. /**
  87497. * Execute the current task
  87498. * @param scene defines the scene where you want your assets to be loaded
  87499. * @param onSuccess is a callback called when the task is successfully executed
  87500. * @param onError is a callback called if an error occurs
  87501. */
  87502. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87503. throw new Error("runTask is not implemented");
  87504. };
  87505. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  87506. this._taskState = AssetTaskState.ERROR;
  87507. this._errorObject = {
  87508. message: message,
  87509. exception: exception
  87510. };
  87511. if (this.onError) {
  87512. this.onError(this, message, exception);
  87513. }
  87514. onError();
  87515. };
  87516. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  87517. try {
  87518. this._taskState = AssetTaskState.DONE;
  87519. this._isCompleted = true;
  87520. if (this.onSuccess) {
  87521. this.onSuccess(this);
  87522. }
  87523. onSuccess();
  87524. }
  87525. catch (e) {
  87526. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  87527. }
  87528. };
  87529. return AbstractAssetTask;
  87530. }());
  87531. BABYLON.AbstractAssetTask = AbstractAssetTask;
  87532. /**
  87533. * Class used to share progress information about assets loading
  87534. */
  87535. var AssetsProgressEvent = /** @class */ (function () {
  87536. /**
  87537. * Creates a {BABYLON.AssetsProgressEvent}
  87538. * @param remainingCount defines the number of remaining tasks to process
  87539. * @param totalCount defines the total number of tasks
  87540. * @param task defines the task that was just processed
  87541. */
  87542. function AssetsProgressEvent(remainingCount, totalCount, task) {
  87543. this.remainingCount = remainingCount;
  87544. this.totalCount = totalCount;
  87545. this.task = task;
  87546. }
  87547. return AssetsProgressEvent;
  87548. }());
  87549. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  87550. /**
  87551. * Define a task used by {BABYLON.AssetsManager} to load meshes
  87552. */
  87553. var MeshAssetTask = /** @class */ (function (_super) {
  87554. __extends(MeshAssetTask, _super);
  87555. /**
  87556. * Creates a new {BABYLON.MeshAssetTask}
  87557. * @param name defines the name of the task
  87558. * @param meshesNames defines the list of mesh's names you want to load
  87559. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  87560. * @param sceneFilename defines the filename of the scene to load from
  87561. */
  87562. function MeshAssetTask(
  87563. /**
  87564. * Defines the name of the task
  87565. */
  87566. name,
  87567. /**
  87568. * Defines the list of mesh's names you want to load
  87569. */
  87570. meshesNames,
  87571. /**
  87572. * Defines the root url to use as a base to load your meshes and associated resources
  87573. */
  87574. rootUrl,
  87575. /**
  87576. * Defines the filename of the scene to load from
  87577. */
  87578. sceneFilename) {
  87579. var _this = _super.call(this, name) || this;
  87580. _this.name = name;
  87581. _this.meshesNames = meshesNames;
  87582. _this.rootUrl = rootUrl;
  87583. _this.sceneFilename = sceneFilename;
  87584. return _this;
  87585. }
  87586. /**
  87587. * Execute the current task
  87588. * @param scene defines the scene where you want your assets to be loaded
  87589. * @param onSuccess is a callback called when the task is successfully executed
  87590. * @param onError is a callback called if an error occurs
  87591. */
  87592. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87593. var _this = this;
  87594. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  87595. _this.loadedMeshes = meshes;
  87596. _this.loadedParticleSystems = particleSystems;
  87597. _this.loadedSkeletons = skeletons;
  87598. onSuccess();
  87599. }, null, function (scene, message, exception) {
  87600. onError(message, exception);
  87601. });
  87602. };
  87603. return MeshAssetTask;
  87604. }(AbstractAssetTask));
  87605. BABYLON.MeshAssetTask = MeshAssetTask;
  87606. /**
  87607. * Define a task used by {BABYLON.AssetsManager} to load text content
  87608. */
  87609. var TextFileAssetTask = /** @class */ (function (_super) {
  87610. __extends(TextFileAssetTask, _super);
  87611. /**
  87612. * Creates a new TextFileAssetTask object
  87613. * @param name defines the name of the task
  87614. * @param url defines the location of the file to load
  87615. */
  87616. function TextFileAssetTask(
  87617. /**
  87618. * Defines the name of the task
  87619. */
  87620. name,
  87621. /**
  87622. * Defines the location of the file to load
  87623. */
  87624. url) {
  87625. var _this = _super.call(this, name) || this;
  87626. _this.name = name;
  87627. _this.url = url;
  87628. return _this;
  87629. }
  87630. /**
  87631. * Execute the current task
  87632. * @param scene defines the scene where you want your assets to be loaded
  87633. * @param onSuccess is a callback called when the task is successfully executed
  87634. * @param onError is a callback called if an error occurs
  87635. */
  87636. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87637. var _this = this;
  87638. scene._loadFile(this.url, function (data) {
  87639. _this.text = data;
  87640. onSuccess();
  87641. }, undefined, false, false, function (request, exception) {
  87642. if (request) {
  87643. onError(request.status + " " + request.statusText, exception);
  87644. }
  87645. });
  87646. };
  87647. return TextFileAssetTask;
  87648. }(AbstractAssetTask));
  87649. BABYLON.TextFileAssetTask = TextFileAssetTask;
  87650. /**
  87651. * Define a task used by {BABYLON.AssetsManager} to load binary data
  87652. */
  87653. var BinaryFileAssetTask = /** @class */ (function (_super) {
  87654. __extends(BinaryFileAssetTask, _super);
  87655. /**
  87656. * Creates a new BinaryFileAssetTask object
  87657. * @param name defines the name of the new task
  87658. * @param url defines the location of the file to load
  87659. */
  87660. function BinaryFileAssetTask(
  87661. /**
  87662. * Defines the name of the task
  87663. */
  87664. name,
  87665. /**
  87666. * Defines the location of the file to load
  87667. */
  87668. url) {
  87669. var _this = _super.call(this, name) || this;
  87670. _this.name = name;
  87671. _this.url = url;
  87672. return _this;
  87673. }
  87674. /**
  87675. * Execute the current task
  87676. * @param scene defines the scene where you want your assets to be loaded
  87677. * @param onSuccess is a callback called when the task is successfully executed
  87678. * @param onError is a callback called if an error occurs
  87679. */
  87680. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87681. var _this = this;
  87682. scene._loadFile(this.url, function (data) {
  87683. _this.data = data;
  87684. onSuccess();
  87685. }, undefined, true, true, function (request, exception) {
  87686. if (request) {
  87687. onError(request.status + " " + request.statusText, exception);
  87688. }
  87689. });
  87690. };
  87691. return BinaryFileAssetTask;
  87692. }(AbstractAssetTask));
  87693. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  87694. /**
  87695. * Define a task used by {BABYLON.AssetsManager} to load images
  87696. */
  87697. var ImageAssetTask = /** @class */ (function (_super) {
  87698. __extends(ImageAssetTask, _super);
  87699. /**
  87700. * Creates a new ImageAssetTask
  87701. * @param name defines the name of the task
  87702. * @param url defines the location of the image to load
  87703. */
  87704. function ImageAssetTask(
  87705. /**
  87706. * Defines the name of the task
  87707. */
  87708. name,
  87709. /**
  87710. * Defines the location of the image to load
  87711. */
  87712. url) {
  87713. var _this = _super.call(this, name) || this;
  87714. _this.name = name;
  87715. _this.url = url;
  87716. return _this;
  87717. }
  87718. /**
  87719. * Execute the current task
  87720. * @param scene defines the scene where you want your assets to be loaded
  87721. * @param onSuccess is a callback called when the task is successfully executed
  87722. * @param onError is a callback called if an error occurs
  87723. */
  87724. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87725. var _this = this;
  87726. var img = new Image();
  87727. BABYLON.Tools.SetCorsBehavior(this.url, img);
  87728. img.onload = function () {
  87729. _this.image = img;
  87730. onSuccess();
  87731. };
  87732. img.onerror = function (err) {
  87733. onError("Error loading image", err);
  87734. };
  87735. img.src = this.url;
  87736. };
  87737. return ImageAssetTask;
  87738. }(AbstractAssetTask));
  87739. BABYLON.ImageAssetTask = ImageAssetTask;
  87740. /**
  87741. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  87742. */
  87743. var TextureAssetTask = /** @class */ (function (_super) {
  87744. __extends(TextureAssetTask, _super);
  87745. /**
  87746. * Creates a new TextureAssetTask object
  87747. * @param name defines the name of the task
  87748. * @param url defines the location of the file to load
  87749. * @param noMipmap defines if mipmap should not be generated (default is false)
  87750. * @param invertY defines if texture must be inverted on Y axis (default is false)
  87751. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87752. */
  87753. function TextureAssetTask(
  87754. /**
  87755. * Defines the name of the task
  87756. */
  87757. name,
  87758. /**
  87759. * Defines the location of the file to load
  87760. */
  87761. url,
  87762. /**
  87763. * Defines if mipmap should not be generated (default is false)
  87764. */
  87765. noMipmap,
  87766. /**
  87767. * Defines if texture must be inverted on Y axis (default is false)
  87768. */
  87769. invertY,
  87770. /**
  87771. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87772. */
  87773. samplingMode) {
  87774. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87775. var _this = _super.call(this, name) || this;
  87776. _this.name = name;
  87777. _this.url = url;
  87778. _this.noMipmap = noMipmap;
  87779. _this.invertY = invertY;
  87780. _this.samplingMode = samplingMode;
  87781. return _this;
  87782. }
  87783. /**
  87784. * Execute the current task
  87785. * @param scene defines the scene where you want your assets to be loaded
  87786. * @param onSuccess is a callback called when the task is successfully executed
  87787. * @param onError is a callback called if an error occurs
  87788. */
  87789. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87790. var onload = function () {
  87791. onSuccess();
  87792. };
  87793. var onerror = function (message, exception) {
  87794. onError(message, exception);
  87795. };
  87796. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  87797. };
  87798. return TextureAssetTask;
  87799. }(AbstractAssetTask));
  87800. BABYLON.TextureAssetTask = TextureAssetTask;
  87801. /**
  87802. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  87803. */
  87804. var CubeTextureAssetTask = /** @class */ (function (_super) {
  87805. __extends(CubeTextureAssetTask, _super);
  87806. /**
  87807. * Creates a new CubeTextureAssetTask
  87808. * @param name defines the name of the task
  87809. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87810. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87811. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87812. * @param files defines the explicit list of files (undefined by default)
  87813. */
  87814. function CubeTextureAssetTask(
  87815. /**
  87816. * Defines the name of the task
  87817. */
  87818. name,
  87819. /**
  87820. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87821. */
  87822. url,
  87823. /**
  87824. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87825. */
  87826. extensions,
  87827. /**
  87828. * Defines if mipmaps should not be generated (default is false)
  87829. */
  87830. noMipmap,
  87831. /**
  87832. * Defines the explicit list of files (undefined by default)
  87833. */
  87834. files) {
  87835. var _this = _super.call(this, name) || this;
  87836. _this.name = name;
  87837. _this.url = url;
  87838. _this.extensions = extensions;
  87839. _this.noMipmap = noMipmap;
  87840. _this.files = files;
  87841. return _this;
  87842. }
  87843. /**
  87844. * Execute the current task
  87845. * @param scene defines the scene where you want your assets to be loaded
  87846. * @param onSuccess is a callback called when the task is successfully executed
  87847. * @param onError is a callback called if an error occurs
  87848. */
  87849. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87850. var onload = function () {
  87851. onSuccess();
  87852. };
  87853. var onerror = function (message, exception) {
  87854. onError(message, exception);
  87855. };
  87856. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  87857. };
  87858. return CubeTextureAssetTask;
  87859. }(AbstractAssetTask));
  87860. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  87861. /**
  87862. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  87863. */
  87864. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  87865. __extends(HDRCubeTextureAssetTask, _super);
  87866. /**
  87867. * Creates a new HDRCubeTextureAssetTask object
  87868. * @param name defines the name of the task
  87869. * @param url defines the location of the file to load
  87870. * @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.
  87871. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87872. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87873. * @param useInGammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  87874. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87875. */
  87876. function HDRCubeTextureAssetTask(
  87877. /**
  87878. * Defines the name of the task
  87879. */
  87880. name,
  87881. /**
  87882. * Defines the location of the file to load
  87883. */
  87884. url,
  87885. /**
  87886. * 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.
  87887. */
  87888. size,
  87889. /**
  87890. * Defines if mipmaps should not be generated (default is false)
  87891. */
  87892. noMipmap,
  87893. /**
  87894. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87895. */
  87896. generateHarmonics,
  87897. /**
  87898. * 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)
  87899. */
  87900. useInGammaSpace,
  87901. /**
  87902. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87903. */
  87904. usePMREMGenerator) {
  87905. if (noMipmap === void 0) { noMipmap = false; }
  87906. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87907. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87908. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87909. var _this = _super.call(this, name) || this;
  87910. _this.name = name;
  87911. _this.url = url;
  87912. _this.size = size;
  87913. _this.noMipmap = noMipmap;
  87914. _this.generateHarmonics = generateHarmonics;
  87915. _this.useInGammaSpace = useInGammaSpace;
  87916. _this.usePMREMGenerator = usePMREMGenerator;
  87917. return _this;
  87918. }
  87919. /**
  87920. * Execute the current task
  87921. * @param scene defines the scene where you want your assets to be loaded
  87922. * @param onSuccess is a callback called when the task is successfully executed
  87923. * @param onError is a callback called if an error occurs
  87924. */
  87925. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87926. var onload = function () {
  87927. onSuccess();
  87928. };
  87929. var onerror = function (message, exception) {
  87930. onError(message, exception);
  87931. };
  87932. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  87933. };
  87934. return HDRCubeTextureAssetTask;
  87935. }(AbstractAssetTask));
  87936. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  87937. /**
  87938. * This class can be used to easily import assets into a scene
  87939. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  87940. */
  87941. var AssetsManager = /** @class */ (function () {
  87942. /**
  87943. * Creates a new AssetsManager
  87944. * @param scene defines the scene to work on
  87945. */
  87946. function AssetsManager(scene) {
  87947. this._isLoading = false;
  87948. this._tasks = new Array();
  87949. this._waitingTasksCount = 0;
  87950. this._totalTasksCount = 0;
  87951. /**
  87952. * Observable called when all tasks are processed
  87953. */
  87954. this.onTaskSuccessObservable = new BABYLON.Observable();
  87955. /**
  87956. * Observable called when a task had an error
  87957. */
  87958. this.onTaskErrorObservable = new BABYLON.Observable();
  87959. /**
  87960. * Observable called when a task is successful
  87961. */
  87962. this.onTasksDoneObservable = new BABYLON.Observable();
  87963. /**
  87964. * Observable called when a task is done (whatever the result is)
  87965. */
  87966. this.onProgressObservable = new BABYLON.Observable();
  87967. /**
  87968. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  87969. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  87970. */
  87971. this.useDefaultLoadingScreen = true;
  87972. this._scene = scene;
  87973. }
  87974. /**
  87975. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  87976. * @param taskName defines the name of the new task
  87977. * @param meshesNames defines the name of meshes to load
  87978. * @param rootUrl defines the root url to use to locate files
  87979. * @param sceneFilename defines the filename of the scene file
  87980. * @returns a new {BABYLON.MeshAssetTask} object
  87981. */
  87982. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  87983. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  87984. this._tasks.push(task);
  87985. return task;
  87986. };
  87987. /**
  87988. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  87989. * @param taskName defines the name of the new task
  87990. * @param url defines the url of the file to load
  87991. * @returns a new {BABYLON.TextFileAssetTask} object
  87992. */
  87993. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  87994. var task = new TextFileAssetTask(taskName, url);
  87995. this._tasks.push(task);
  87996. return task;
  87997. };
  87998. /**
  87999. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  88000. * @param taskName defines the name of the new task
  88001. * @param url defines the url of the file to load
  88002. * @returns a new {BABYLON.BinaryFileAssetTask} object
  88003. */
  88004. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  88005. var task = new BinaryFileAssetTask(taskName, url);
  88006. this._tasks.push(task);
  88007. return task;
  88008. };
  88009. /**
  88010. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  88011. * @param taskName defines the name of the new task
  88012. * @param url defines the url of the file to load
  88013. * @returns a new {BABYLON.ImageAssetTask} object
  88014. */
  88015. AssetsManager.prototype.addImageTask = function (taskName, url) {
  88016. var task = new ImageAssetTask(taskName, url);
  88017. this._tasks.push(task);
  88018. return task;
  88019. };
  88020. /**
  88021. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  88022. * @param taskName defines the name of the new task
  88023. * @param url defines the url of the file to load
  88024. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88025. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  88026. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  88027. * @returns a new {BABYLON.TextureAssetTask} object
  88028. */
  88029. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  88030. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88031. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  88032. this._tasks.push(task);
  88033. return task;
  88034. };
  88035. /**
  88036. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  88037. * @param taskName defines the name of the new task
  88038. * @param url defines the url of the file to load
  88039. * @param extensions defines the extension to use to load the cube map (can be null)
  88040. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88041. * @param files defines the list of files to load (can be null)
  88042. * @returns a new {BABYLON.CubeTextureAssetTask} object
  88043. */
  88044. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  88045. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  88046. this._tasks.push(task);
  88047. return task;
  88048. };
  88049. /**
  88050. *
  88051. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  88052. * @param taskName defines the name of the new task
  88053. * @param url defines the url of the file to load
  88054. * @param size defines the size you want for the cubemap (can be null)
  88055. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88056. * @param generateHarmonics defines if you want to automatically generate (true by default)
  88057. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  88058. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  88059. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  88060. */
  88061. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  88062. if (noMipmap === void 0) { noMipmap = false; }
  88063. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88064. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88065. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88066. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  88067. this._tasks.push(task);
  88068. return task;
  88069. };
  88070. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  88071. var _this = this;
  88072. this._waitingTasksCount--;
  88073. try {
  88074. if (task.taskState === AssetTaskState.DONE) {
  88075. // Let's remove successfull tasks
  88076. BABYLON.Tools.SetImmediate(function () {
  88077. var index = _this._tasks.indexOf(task);
  88078. if (index > -1) {
  88079. _this._tasks.splice(index, 1);
  88080. }
  88081. });
  88082. }
  88083. if (this.onProgress) {
  88084. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  88085. }
  88086. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  88087. }
  88088. catch (e) {
  88089. BABYLON.Tools.Error("Error running progress callbacks.");
  88090. console.log(e);
  88091. }
  88092. if (this._waitingTasksCount === 0) {
  88093. try {
  88094. if (this.onFinish) {
  88095. this.onFinish(this._tasks);
  88096. }
  88097. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88098. }
  88099. catch (e) {
  88100. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  88101. console.log(e);
  88102. }
  88103. this._isLoading = false;
  88104. this._scene.getEngine().hideLoadingUI();
  88105. }
  88106. };
  88107. AssetsManager.prototype._runTask = function (task) {
  88108. var _this = this;
  88109. var done = function () {
  88110. try {
  88111. if (_this.onTaskSuccess) {
  88112. _this.onTaskSuccess(task);
  88113. }
  88114. _this.onTaskSuccessObservable.notifyObservers(task);
  88115. _this._decreaseWaitingTasksCount(task);
  88116. }
  88117. catch (e) {
  88118. error("Error executing task success callbacks", e);
  88119. }
  88120. };
  88121. var error = function (message, exception) {
  88122. task._setErrorObject(message, exception);
  88123. if (_this.onTaskError) {
  88124. _this.onTaskError(task);
  88125. }
  88126. _this.onTaskErrorObservable.notifyObservers(task);
  88127. _this._decreaseWaitingTasksCount(task);
  88128. };
  88129. task.run(this._scene, done, error);
  88130. };
  88131. /**
  88132. * Reset the {BABYLON.AssetsManager} and remove all tasks
  88133. * @return the current instance of the {BABYLON.AssetsManager}
  88134. */
  88135. AssetsManager.prototype.reset = function () {
  88136. this._isLoading = false;
  88137. this._tasks = new Array();
  88138. return this;
  88139. };
  88140. /**
  88141. * Start the loading process
  88142. * @return the current instance of the {BABYLON.AssetsManager}
  88143. */
  88144. AssetsManager.prototype.load = function () {
  88145. if (this._isLoading) {
  88146. return this;
  88147. }
  88148. this._isLoading = true;
  88149. this._waitingTasksCount = this._tasks.length;
  88150. this._totalTasksCount = this._tasks.length;
  88151. if (this._waitingTasksCount === 0) {
  88152. this._isLoading = false;
  88153. if (this.onFinish) {
  88154. this.onFinish(this._tasks);
  88155. }
  88156. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88157. return this;
  88158. }
  88159. if (this.useDefaultLoadingScreen) {
  88160. this._scene.getEngine().displayLoadingUI();
  88161. }
  88162. for (var index = 0; index < this._tasks.length; index++) {
  88163. var task = this._tasks[index];
  88164. this._runTask(task);
  88165. }
  88166. return this;
  88167. };
  88168. return AssetsManager;
  88169. }());
  88170. BABYLON.AssetsManager = AssetsManager;
  88171. })(BABYLON || (BABYLON = {}));
  88172. //# sourceMappingURL=babylon.assetsManager.js.map
  88173. "use strict";
  88174. var BABYLON;
  88175. (function (BABYLON) {
  88176. var serializedGeometries = [];
  88177. var serializeGeometry = function (geometry, serializationGeometries) {
  88178. if (serializedGeometries[geometry.id]) {
  88179. return;
  88180. }
  88181. if (geometry.doNotSerialize) {
  88182. return;
  88183. }
  88184. if (geometry instanceof BABYLON.BoxGeometry) {
  88185. serializationGeometries.boxes.push(geometry.serialize());
  88186. }
  88187. else if (geometry instanceof BABYLON.SphereGeometry) {
  88188. serializationGeometries.spheres.push(geometry.serialize());
  88189. }
  88190. else if (geometry instanceof BABYLON.CylinderGeometry) {
  88191. serializationGeometries.cylinders.push(geometry.serialize());
  88192. }
  88193. else if (geometry instanceof BABYLON.TorusGeometry) {
  88194. serializationGeometries.toruses.push(geometry.serialize());
  88195. }
  88196. else if (geometry instanceof BABYLON.GroundGeometry) {
  88197. serializationGeometries.grounds.push(geometry.serialize());
  88198. }
  88199. else if (geometry instanceof BABYLON.Plane) {
  88200. serializationGeometries.planes.push(geometry.serialize());
  88201. }
  88202. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  88203. serializationGeometries.torusKnots.push(geometry.serialize());
  88204. }
  88205. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  88206. throw new Error("Unknown primitive type");
  88207. }
  88208. else {
  88209. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  88210. }
  88211. serializedGeometries[geometry.id] = true;
  88212. };
  88213. var serializeMesh = function (mesh, serializationScene) {
  88214. var serializationObject = {};
  88215. // Geometry
  88216. var geometry = mesh._geometry;
  88217. if (geometry) {
  88218. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  88219. // 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
  88220. serializeGeometry(geometry, serializationScene.geometries);
  88221. }
  88222. }
  88223. // Custom
  88224. if (mesh.serialize) {
  88225. mesh.serialize(serializationObject);
  88226. }
  88227. return serializationObject;
  88228. };
  88229. var finalizeSingleMesh = function (mesh, serializationObject) {
  88230. //only works if the mesh is already loaded
  88231. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88232. //serialize material
  88233. if (mesh.material) {
  88234. if (mesh.material instanceof BABYLON.StandardMaterial) {
  88235. serializationObject.materials = serializationObject.materials || [];
  88236. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88237. serializationObject.materials.push(mesh.material.serialize());
  88238. }
  88239. }
  88240. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  88241. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  88242. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88243. serializationObject.multiMaterials.push(mesh.material.serialize());
  88244. }
  88245. }
  88246. }
  88247. //serialize geometry
  88248. var geometry = mesh._geometry;
  88249. if (geometry) {
  88250. if (!serializationObject.geometries) {
  88251. serializationObject.geometries = {};
  88252. serializationObject.geometries.boxes = [];
  88253. serializationObject.geometries.spheres = [];
  88254. serializationObject.geometries.cylinders = [];
  88255. serializationObject.geometries.toruses = [];
  88256. serializationObject.geometries.grounds = [];
  88257. serializationObject.geometries.planes = [];
  88258. serializationObject.geometries.torusKnots = [];
  88259. serializationObject.geometries.vertexData = [];
  88260. }
  88261. serializeGeometry(geometry, serializationObject.geometries);
  88262. }
  88263. // Skeletons
  88264. if (mesh.skeleton) {
  88265. serializationObject.skeletons = serializationObject.skeletons || [];
  88266. serializationObject.skeletons.push(mesh.skeleton.serialize());
  88267. }
  88268. //serialize the actual mesh
  88269. serializationObject.meshes = serializationObject.meshes || [];
  88270. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88271. }
  88272. };
  88273. var SceneSerializer = /** @class */ (function () {
  88274. function SceneSerializer() {
  88275. }
  88276. SceneSerializer.ClearCache = function () {
  88277. serializedGeometries = [];
  88278. };
  88279. SceneSerializer.Serialize = function (scene) {
  88280. var serializationObject = {};
  88281. SceneSerializer.ClearCache();
  88282. // Scene
  88283. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  88284. serializationObject.autoClear = scene.autoClear;
  88285. serializationObject.clearColor = scene.clearColor.asArray();
  88286. serializationObject.ambientColor = scene.ambientColor.asArray();
  88287. serializationObject.gravity = scene.gravity.asArray();
  88288. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  88289. serializationObject.workerCollisions = scene.workerCollisions;
  88290. // Fog
  88291. if (scene.fogMode && scene.fogMode !== 0) {
  88292. serializationObject.fogMode = scene.fogMode;
  88293. serializationObject.fogColor = scene.fogColor.asArray();
  88294. serializationObject.fogStart = scene.fogStart;
  88295. serializationObject.fogEnd = scene.fogEnd;
  88296. serializationObject.fogDensity = scene.fogDensity;
  88297. }
  88298. //Physics
  88299. if (scene.isPhysicsEnabled()) {
  88300. var physicEngine = scene.getPhysicsEngine();
  88301. if (physicEngine) {
  88302. serializationObject.physicsEnabled = true;
  88303. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  88304. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  88305. }
  88306. }
  88307. // Metadata
  88308. if (scene.metadata) {
  88309. serializationObject.metadata = scene.metadata;
  88310. }
  88311. // Morph targets
  88312. serializationObject.morphTargetManagers = [];
  88313. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  88314. var abstractMesh = _a[_i];
  88315. var manager = abstractMesh.morphTargetManager;
  88316. if (manager) {
  88317. serializationObject.morphTargetManagers.push(manager.serialize());
  88318. }
  88319. }
  88320. // Lights
  88321. serializationObject.lights = [];
  88322. var index;
  88323. var light;
  88324. for (index = 0; index < scene.lights.length; index++) {
  88325. light = scene.lights[index];
  88326. if (!light.doNotSerialize) {
  88327. serializationObject.lights.push(light.serialize());
  88328. }
  88329. }
  88330. // Cameras
  88331. serializationObject.cameras = [];
  88332. for (index = 0; index < scene.cameras.length; index++) {
  88333. var camera = scene.cameras[index];
  88334. if (!camera.doNotSerialize) {
  88335. serializationObject.cameras.push(camera.serialize());
  88336. }
  88337. }
  88338. if (scene.activeCamera) {
  88339. serializationObject.activeCameraID = scene.activeCamera.id;
  88340. }
  88341. // Animations
  88342. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  88343. // Materials
  88344. serializationObject.materials = [];
  88345. serializationObject.multiMaterials = [];
  88346. var material;
  88347. for (index = 0; index < scene.materials.length; index++) {
  88348. material = scene.materials[index];
  88349. if (!material.doNotSerialize) {
  88350. serializationObject.materials.push(material.serialize());
  88351. }
  88352. }
  88353. // MultiMaterials
  88354. serializationObject.multiMaterials = [];
  88355. for (index = 0; index < scene.multiMaterials.length; index++) {
  88356. var multiMaterial = scene.multiMaterials[index];
  88357. serializationObject.multiMaterials.push(multiMaterial.serialize());
  88358. }
  88359. // Environment texture
  88360. if (scene.environmentTexture) {
  88361. serializationObject.environmentTexture = scene.environmentTexture.name;
  88362. }
  88363. // Skeletons
  88364. serializationObject.skeletons = [];
  88365. for (index = 0; index < scene.skeletons.length; index++) {
  88366. var skeleton = scene.skeletons[index];
  88367. if (!skeleton.doNotSerialize) {
  88368. serializationObject.skeletons.push(skeleton.serialize());
  88369. }
  88370. }
  88371. // Transform nodes
  88372. serializationObject.transformNodes = [];
  88373. for (index = 0; index < scene.transformNodes.length; index++) {
  88374. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  88375. }
  88376. // Geometries
  88377. serializationObject.geometries = {};
  88378. serializationObject.geometries.boxes = [];
  88379. serializationObject.geometries.spheres = [];
  88380. serializationObject.geometries.cylinders = [];
  88381. serializationObject.geometries.toruses = [];
  88382. serializationObject.geometries.grounds = [];
  88383. serializationObject.geometries.planes = [];
  88384. serializationObject.geometries.torusKnots = [];
  88385. serializationObject.geometries.vertexData = [];
  88386. serializedGeometries = [];
  88387. var geometries = scene.getGeometries();
  88388. for (index = 0; index < geometries.length; index++) {
  88389. var geometry = geometries[index];
  88390. if (geometry.isReady()) {
  88391. serializeGeometry(geometry, serializationObject.geometries);
  88392. }
  88393. }
  88394. // Meshes
  88395. serializationObject.meshes = [];
  88396. for (index = 0; index < scene.meshes.length; index++) {
  88397. var abstractMesh = scene.meshes[index];
  88398. if (abstractMesh instanceof BABYLON.Mesh) {
  88399. var mesh = abstractMesh;
  88400. if (!mesh.doNotSerialize) {
  88401. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88402. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88403. }
  88404. }
  88405. }
  88406. }
  88407. // Particles Systems
  88408. serializationObject.particleSystems = [];
  88409. for (index = 0; index < scene.particleSystems.length; index++) {
  88410. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  88411. }
  88412. // Lens flares
  88413. serializationObject.lensFlareSystems = [];
  88414. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  88415. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  88416. }
  88417. // Shadows
  88418. serializationObject.shadowGenerators = [];
  88419. for (index = 0; index < scene.lights.length; index++) {
  88420. light = scene.lights[index];
  88421. var shadowGenerator = light.getShadowGenerator();
  88422. if (shadowGenerator) {
  88423. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  88424. }
  88425. }
  88426. // Action Manager
  88427. if (scene.actionManager) {
  88428. serializationObject.actions = scene.actionManager.serialize("scene");
  88429. }
  88430. // Audio
  88431. serializationObject.sounds = [];
  88432. for (index = 0; index < scene.soundTracks.length; index++) {
  88433. var soundtrack = scene.soundTracks[index];
  88434. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  88435. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  88436. }
  88437. }
  88438. return serializationObject;
  88439. };
  88440. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  88441. if (withParents === void 0) { withParents = false; }
  88442. if (withChildren === void 0) { withChildren = false; }
  88443. var serializationObject = {};
  88444. SceneSerializer.ClearCache();
  88445. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  88446. if (withParents || withChildren) {
  88447. //deliberate for loop! not for each, appended should be processed as well.
  88448. for (var i = 0; i < toSerialize.length; ++i) {
  88449. if (withChildren) {
  88450. toSerialize[i].getDescendants().forEach(function (node) {
  88451. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  88452. toSerialize.push(node);
  88453. }
  88454. });
  88455. }
  88456. //make sure the array doesn't contain the object already
  88457. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  88458. toSerialize.push(toSerialize[i].parent);
  88459. }
  88460. }
  88461. }
  88462. toSerialize.forEach(function (mesh) {
  88463. finalizeSingleMesh(mesh, serializationObject);
  88464. });
  88465. return serializationObject;
  88466. };
  88467. return SceneSerializer;
  88468. }());
  88469. BABYLON.SceneSerializer = SceneSerializer;
  88470. })(BABYLON || (BABYLON = {}));
  88471. //# sourceMappingURL=babylon.sceneSerializer.js.map
  88472. "use strict";
  88473. var BABYLON;
  88474. (function (BABYLON) {
  88475. var ReflectionProbe = /** @class */ (function () {
  88476. function ReflectionProbe(name, size, scene, generateMipMaps) {
  88477. if (generateMipMaps === void 0) { generateMipMaps = true; }
  88478. var _this = this;
  88479. this.name = name;
  88480. this._viewMatrix = BABYLON.Matrix.Identity();
  88481. this._target = BABYLON.Vector3.Zero();
  88482. this._add = BABYLON.Vector3.Zero();
  88483. this._invertYAxis = false;
  88484. this.position = BABYLON.Vector3.Zero();
  88485. this._scene = scene;
  88486. this._scene.reflectionProbes.push(this);
  88487. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  88488. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  88489. switch (faceIndex) {
  88490. case 0:
  88491. _this._add.copyFromFloats(1, 0, 0);
  88492. break;
  88493. case 1:
  88494. _this._add.copyFromFloats(-1, 0, 0);
  88495. break;
  88496. case 2:
  88497. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  88498. break;
  88499. case 3:
  88500. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  88501. break;
  88502. case 4:
  88503. _this._add.copyFromFloats(0, 0, 1);
  88504. break;
  88505. case 5:
  88506. _this._add.copyFromFloats(0, 0, -1);
  88507. break;
  88508. }
  88509. if (_this._attachedMesh) {
  88510. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  88511. }
  88512. _this.position.addToRef(_this._add, _this._target);
  88513. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  88514. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  88515. scene._forcedViewPosition = _this.position;
  88516. });
  88517. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  88518. scene._forcedViewPosition = null;
  88519. scene.updateTransformMatrix(true);
  88520. });
  88521. if (scene.activeCamera) {
  88522. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  88523. }
  88524. }
  88525. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  88526. get: function () {
  88527. return this._renderTargetTexture.samples;
  88528. },
  88529. set: function (value) {
  88530. this._renderTargetTexture.samples = value;
  88531. },
  88532. enumerable: true,
  88533. configurable: true
  88534. });
  88535. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  88536. get: function () {
  88537. return this._renderTargetTexture.refreshRate;
  88538. },
  88539. set: function (value) {
  88540. this._renderTargetTexture.refreshRate = value;
  88541. },
  88542. enumerable: true,
  88543. configurable: true
  88544. });
  88545. ReflectionProbe.prototype.getScene = function () {
  88546. return this._scene;
  88547. };
  88548. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  88549. get: function () {
  88550. return this._renderTargetTexture;
  88551. },
  88552. enumerable: true,
  88553. configurable: true
  88554. });
  88555. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  88556. get: function () {
  88557. return this._renderTargetTexture.renderList;
  88558. },
  88559. enumerable: true,
  88560. configurable: true
  88561. });
  88562. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  88563. this._attachedMesh = mesh;
  88564. };
  88565. /**
  88566. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  88567. *
  88568. * @param renderingGroupId The rendering group id corresponding to its index
  88569. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  88570. */
  88571. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  88572. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  88573. };
  88574. ReflectionProbe.prototype.dispose = function () {
  88575. var index = this._scene.reflectionProbes.indexOf(this);
  88576. if (index !== -1) {
  88577. // Remove from the scene if found
  88578. this._scene.reflectionProbes.splice(index, 1);
  88579. }
  88580. if (this._renderTargetTexture) {
  88581. this._renderTargetTexture.dispose();
  88582. this._renderTargetTexture = null;
  88583. }
  88584. };
  88585. return ReflectionProbe;
  88586. }());
  88587. BABYLON.ReflectionProbe = ReflectionProbe;
  88588. })(BABYLON || (BABYLON = {}));
  88589. //# sourceMappingURL=babylon.reflectionProbe.js.map
  88590. "use strict";
  88591. var BABYLON;
  88592. (function (BABYLON) {
  88593. var Layer = /** @class */ (function () {
  88594. function Layer(name, imgUrl, scene, isBackground, color) {
  88595. this.name = name;
  88596. this.scale = new BABYLON.Vector2(1, 1);
  88597. this.offset = new BABYLON.Vector2(0, 0);
  88598. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  88599. this.layerMask = 0x0FFFFFFF;
  88600. this._vertexBuffers = {};
  88601. // Events
  88602. /**
  88603. * An event triggered when the layer is disposed.
  88604. * @type {BABYLON.Observable}
  88605. */
  88606. this.onDisposeObservable = new BABYLON.Observable();
  88607. /**
  88608. * An event triggered before rendering the scene
  88609. * @type {BABYLON.Observable}
  88610. */
  88611. this.onBeforeRenderObservable = new BABYLON.Observable();
  88612. /**
  88613. * An event triggered after rendering the scene
  88614. * @type {BABYLON.Observable}
  88615. */
  88616. this.onAfterRenderObservable = new BABYLON.Observable();
  88617. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  88618. this.isBackground = isBackground === undefined ? true : isBackground;
  88619. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  88620. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  88621. this._scene.layers.push(this);
  88622. var engine = this._scene.getEngine();
  88623. // VBO
  88624. var vertices = [];
  88625. vertices.push(1, 1);
  88626. vertices.push(-1, 1);
  88627. vertices.push(-1, -1);
  88628. vertices.push(1, -1);
  88629. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  88630. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  88631. this._createIndexBuffer();
  88632. // Effects
  88633. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  88634. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  88635. }
  88636. Object.defineProperty(Layer.prototype, "onDispose", {
  88637. set: function (callback) {
  88638. if (this._onDisposeObserver) {
  88639. this.onDisposeObservable.remove(this._onDisposeObserver);
  88640. }
  88641. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  88642. },
  88643. enumerable: true,
  88644. configurable: true
  88645. });
  88646. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  88647. set: function (callback) {
  88648. if (this._onBeforeRenderObserver) {
  88649. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  88650. }
  88651. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  88652. },
  88653. enumerable: true,
  88654. configurable: true
  88655. });
  88656. Object.defineProperty(Layer.prototype, "onAfterRender", {
  88657. set: function (callback) {
  88658. if (this._onAfterRenderObserver) {
  88659. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  88660. }
  88661. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  88662. },
  88663. enumerable: true,
  88664. configurable: true
  88665. });
  88666. Layer.prototype._createIndexBuffer = function () {
  88667. var engine = this._scene.getEngine();
  88668. // Indices
  88669. var indices = [];
  88670. indices.push(0);
  88671. indices.push(1);
  88672. indices.push(2);
  88673. indices.push(0);
  88674. indices.push(2);
  88675. indices.push(3);
  88676. this._indexBuffer = engine.createIndexBuffer(indices);
  88677. };
  88678. Layer.prototype._rebuild = function () {
  88679. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88680. if (vb) {
  88681. vb._rebuild();
  88682. }
  88683. this._createIndexBuffer();
  88684. };
  88685. Layer.prototype.render = function () {
  88686. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  88687. // Check
  88688. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  88689. return;
  88690. var engine = this._scene.getEngine();
  88691. this.onBeforeRenderObservable.notifyObservers(this);
  88692. // Render
  88693. engine.enableEffect(currentEffect);
  88694. engine.setState(false);
  88695. // Texture
  88696. currentEffect.setTexture("textureSampler", this.texture);
  88697. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  88698. // Color
  88699. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  88700. // Scale / offset
  88701. currentEffect.setVector2("offset", this.offset);
  88702. currentEffect.setVector2("scale", this.scale);
  88703. // VBOs
  88704. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  88705. // Draw order
  88706. if (!this.alphaTest) {
  88707. engine.setAlphaMode(this.alphaBlendingMode);
  88708. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88709. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  88710. }
  88711. else {
  88712. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88713. }
  88714. this.onAfterRenderObservable.notifyObservers(this);
  88715. };
  88716. Layer.prototype.dispose = function () {
  88717. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88718. if (vertexBuffer) {
  88719. vertexBuffer.dispose();
  88720. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88721. }
  88722. if (this._indexBuffer) {
  88723. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88724. this._indexBuffer = null;
  88725. }
  88726. if (this.texture) {
  88727. this.texture.dispose();
  88728. this.texture = null;
  88729. }
  88730. // Remove from scene
  88731. var index = this._scene.layers.indexOf(this);
  88732. this._scene.layers.splice(index, 1);
  88733. // Callback
  88734. this.onDisposeObservable.notifyObservers(this);
  88735. this.onDisposeObservable.clear();
  88736. this.onAfterRenderObservable.clear();
  88737. this.onBeforeRenderObservable.clear();
  88738. };
  88739. return Layer;
  88740. }());
  88741. BABYLON.Layer = Layer;
  88742. })(BABYLON || (BABYLON = {}));
  88743. //# sourceMappingURL=babylon.layer.js.map
  88744. "use strict";
  88745. var BABYLON;
  88746. (function (BABYLON) {
  88747. var TextureTools = /** @class */ (function () {
  88748. function TextureTools() {
  88749. }
  88750. /**
  88751. * Uses the GPU to create a copy texture rescaled at a given size
  88752. * @param texture Texture to copy from
  88753. * @param width Desired width
  88754. * @param height Desired height
  88755. * @return Generated texture
  88756. */
  88757. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  88758. if (useBilinearMode === void 0) { useBilinearMode = true; }
  88759. var scene = texture.getScene();
  88760. var engine = scene.getEngine();
  88761. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  88762. rtt.wrapU = texture.wrapU;
  88763. rtt.wrapV = texture.wrapV;
  88764. rtt.uOffset = texture.uOffset;
  88765. rtt.vOffset = texture.vOffset;
  88766. rtt.uScale = texture.uScale;
  88767. rtt.vScale = texture.vScale;
  88768. rtt.uAng = texture.uAng;
  88769. rtt.vAng = texture.vAng;
  88770. rtt.wAng = texture.wAng;
  88771. rtt.coordinatesIndex = texture.coordinatesIndex;
  88772. rtt.level = texture.level;
  88773. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  88774. rtt._texture.isReady = false;
  88775. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88776. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88777. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  88778. passPostProcess.getEffect().executeWhenCompiled(function () {
  88779. passPostProcess.onApply = function (effect) {
  88780. effect.setTexture("textureSampler", texture);
  88781. };
  88782. var internalTexture = rtt.getInternalTexture();
  88783. if (internalTexture) {
  88784. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  88785. engine.unBindFramebuffer(internalTexture);
  88786. rtt.disposeFramebufferObjects();
  88787. passPostProcess.dispose();
  88788. internalTexture.isReady = true;
  88789. }
  88790. });
  88791. return rtt;
  88792. };
  88793. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  88794. if (!scene._environmentBRDFTexture) {
  88795. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88796. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88797. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88798. scene._environmentBRDFTexture = texture;
  88799. }
  88800. return scene._environmentBRDFTexture;
  88801. };
  88802. 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=";
  88803. return TextureTools;
  88804. }());
  88805. BABYLON.TextureTools = TextureTools;
  88806. })(BABYLON || (BABYLON = {}));
  88807. //# sourceMappingURL=babylon.textureTools.js.map
  88808. "use strict";
  88809. var BABYLON;
  88810. (function (BABYLON) {
  88811. var FramingBehavior = /** @class */ (function () {
  88812. function FramingBehavior() {
  88813. this._mode = FramingBehavior.FitFrustumSidesMode;
  88814. this._radiusScale = 1.0;
  88815. this._positionScale = 0.5;
  88816. this._defaultElevation = 0.3;
  88817. this._elevationReturnTime = 1500;
  88818. this._elevationReturnWaitTime = 1000;
  88819. this._zoomStopsAnimation = false;
  88820. this._framingTime = 1500;
  88821. this._isPointerDown = false;
  88822. this._lastInteractionTime = -Infinity;
  88823. // Framing control
  88824. this._animatables = new Array();
  88825. this._betaIsAnimating = false;
  88826. }
  88827. Object.defineProperty(FramingBehavior.prototype, "name", {
  88828. get: function () {
  88829. return "Framing";
  88830. },
  88831. enumerable: true,
  88832. configurable: true
  88833. });
  88834. Object.defineProperty(FramingBehavior.prototype, "mode", {
  88835. /**
  88836. * Gets current mode used by the behavior.
  88837. */
  88838. get: function () {
  88839. return this._mode;
  88840. },
  88841. /**
  88842. * Sets the current mode used by the behavior
  88843. */
  88844. set: function (mode) {
  88845. this._mode = mode;
  88846. },
  88847. enumerable: true,
  88848. configurable: true
  88849. });
  88850. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  88851. /**
  88852. * Gets the scale applied to the radius
  88853. */
  88854. get: function () {
  88855. return this._radiusScale;
  88856. },
  88857. /**
  88858. * Sets the scale applied to the radius (1 by default)
  88859. */
  88860. set: function (radius) {
  88861. this._radiusScale = radius;
  88862. },
  88863. enumerable: true,
  88864. configurable: true
  88865. });
  88866. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  88867. /**
  88868. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88869. */
  88870. get: function () {
  88871. return this._positionScale;
  88872. },
  88873. /**
  88874. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88875. */
  88876. set: function (scale) {
  88877. this._positionScale = scale;
  88878. },
  88879. enumerable: true,
  88880. configurable: true
  88881. });
  88882. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  88883. /**
  88884. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88885. * behaviour is triggered, in radians.
  88886. */
  88887. get: function () {
  88888. return this._defaultElevation;
  88889. },
  88890. /**
  88891. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88892. * behaviour is triggered, in radians.
  88893. */
  88894. set: function (elevation) {
  88895. this._defaultElevation = elevation;
  88896. },
  88897. enumerable: true,
  88898. configurable: true
  88899. });
  88900. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  88901. /**
  88902. * Gets the time (in milliseconds) taken to return to the default beta position.
  88903. * Negative value indicates camera should not return to default.
  88904. */
  88905. get: function () {
  88906. return this._elevationReturnTime;
  88907. },
  88908. /**
  88909. * Sets the time (in milliseconds) taken to return to the default beta position.
  88910. * Negative value indicates camera should not return to default.
  88911. */
  88912. set: function (speed) {
  88913. this._elevationReturnTime = speed;
  88914. },
  88915. enumerable: true,
  88916. configurable: true
  88917. });
  88918. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  88919. /**
  88920. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88921. */
  88922. get: function () {
  88923. return this._elevationReturnWaitTime;
  88924. },
  88925. /**
  88926. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88927. */
  88928. set: function (time) {
  88929. this._elevationReturnWaitTime = time;
  88930. },
  88931. enumerable: true,
  88932. configurable: true
  88933. });
  88934. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  88935. /**
  88936. * Gets the flag that indicates if user zooming should stop animation.
  88937. */
  88938. get: function () {
  88939. return this._zoomStopsAnimation;
  88940. },
  88941. /**
  88942. * Sets the flag that indicates if user zooming should stop animation.
  88943. */
  88944. set: function (flag) {
  88945. this._zoomStopsAnimation = flag;
  88946. },
  88947. enumerable: true,
  88948. configurable: true
  88949. });
  88950. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  88951. /**
  88952. * Gets the transition time when framing the mesh, in milliseconds
  88953. */
  88954. get: function () {
  88955. return this._framingTime;
  88956. },
  88957. /**
  88958. * Sets the transition time when framing the mesh, in milliseconds
  88959. */
  88960. set: function (time) {
  88961. this._framingTime = time;
  88962. },
  88963. enumerable: true,
  88964. configurable: true
  88965. });
  88966. FramingBehavior.prototype.init = function () {
  88967. // Do notihng
  88968. };
  88969. FramingBehavior.prototype.attach = function (camera) {
  88970. var _this = this;
  88971. this._attachedCamera = camera;
  88972. var scene = this._attachedCamera.getScene();
  88973. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  88974. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  88975. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88976. _this._isPointerDown = true;
  88977. return;
  88978. }
  88979. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88980. _this._isPointerDown = false;
  88981. }
  88982. });
  88983. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88984. if (mesh) {
  88985. _this.zoomOnMesh(mesh);
  88986. }
  88987. });
  88988. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88989. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88990. _this._applyUserInteraction();
  88991. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  88992. // back to the default position after a given timeout
  88993. _this._maintainCameraAboveGround();
  88994. });
  88995. };
  88996. FramingBehavior.prototype.detach = function () {
  88997. if (!this._attachedCamera) {
  88998. return;
  88999. }
  89000. var scene = this._attachedCamera.getScene();
  89001. if (this._onPrePointerObservableObserver) {
  89002. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89003. }
  89004. if (this._onAfterCheckInputsObserver) {
  89005. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89006. }
  89007. if (this._onMeshTargetChangedObserver) {
  89008. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89009. }
  89010. this._attachedCamera = null;
  89011. };
  89012. /**
  89013. * Targets the given mesh and updates zoom level accordingly.
  89014. * @param mesh The mesh to target.
  89015. * @param radius Optional. If a cached radius position already exists, overrides default.
  89016. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89017. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89018. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89019. */
  89020. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89021. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89022. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89023. mesh.computeWorldMatrix(true);
  89024. var boundingBox = mesh.getBoundingInfo().boundingBox;
  89025. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  89026. };
  89027. /**
  89028. * Targets the given mesh with its children and updates zoom level accordingly.
  89029. * @param mesh The mesh to target.
  89030. * @param radius Optional. If a cached radius position already exists, overrides default.
  89031. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89032. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89033. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89034. */
  89035. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89036. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89037. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89038. mesh.computeWorldMatrix(true);
  89039. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  89040. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  89041. };
  89042. /**
  89043. * Targets the given meshes with their children and updates zoom level accordingly.
  89044. * @param meshes The mesh to target.
  89045. * @param radius Optional. If a cached radius position already exists, overrides default.
  89046. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89047. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89048. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89049. */
  89050. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  89051. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89052. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89053. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  89054. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  89055. for (var i = 0; i < meshes.length; i++) {
  89056. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  89057. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  89058. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  89059. }
  89060. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  89061. };
  89062. /**
  89063. * Targets the given mesh and updates zoom level accordingly.
  89064. * @param mesh The mesh to target.
  89065. * @param radius Optional. If a cached radius position already exists, overrides default.
  89066. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89067. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89068. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89069. */
  89070. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  89071. var _this = this;
  89072. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89073. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89074. var zoomTarget;
  89075. if (!this._attachedCamera) {
  89076. return;
  89077. }
  89078. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  89079. var bottom = minimumWorld.y;
  89080. var top = maximumWorld.y;
  89081. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  89082. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  89083. if (focusOnOriginXZ) {
  89084. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  89085. }
  89086. else {
  89087. var centerWorld = minimumWorld.add(radiusWorld);
  89088. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  89089. }
  89090. if (!this._vectorTransition) {
  89091. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  89092. }
  89093. this._betaIsAnimating = true;
  89094. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  89095. if (animatable) {
  89096. this._animatables.push(animatable);
  89097. }
  89098. // sets the radius and lower radius bounds
  89099. // Small delta ensures camera is not always at lower zoom limit.
  89100. var radius = 0;
  89101. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  89102. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89103. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  89104. radius = position;
  89105. }
  89106. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89107. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89108. if (this._attachedCamera.lowerRadiusLimit === null) {
  89109. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  89110. }
  89111. }
  89112. // Set sensibilities
  89113. var extend = maximumWorld.subtract(minimumWorld).length();
  89114. this._attachedCamera.panningSensibility = 5000 / extend;
  89115. this._attachedCamera.wheelPrecision = 100 / radius;
  89116. // transition to new radius
  89117. if (!this._radiusTransition) {
  89118. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89119. }
  89120. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  89121. _this.stopAllAnimations();
  89122. if (onAnimationEnd) {
  89123. onAnimationEnd();
  89124. }
  89125. if (_this._attachedCamera) {
  89126. _this._attachedCamera.storeState();
  89127. }
  89128. });
  89129. if (animatable) {
  89130. this._animatables.push(animatable);
  89131. }
  89132. };
  89133. /**
  89134. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  89135. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  89136. * frustum width.
  89137. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  89138. * to fully enclose the mesh in the viewing frustum.
  89139. */
  89140. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  89141. var size = maximumWorld.subtract(minimumWorld);
  89142. var boxVectorGlobalDiagonal = size.length();
  89143. var frustumSlope = this._getFrustumSlope();
  89144. // Formula for setting distance
  89145. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  89146. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  89147. // Horizon distance
  89148. var radius = radiusWithoutFraming * this._radiusScale;
  89149. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  89150. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  89151. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  89152. var camera = this._attachedCamera;
  89153. if (!camera) {
  89154. return 0;
  89155. }
  89156. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89157. // Don't exceed the requested limit
  89158. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  89159. }
  89160. // Don't exceed the upper radius limit
  89161. if (camera.upperRadiusLimit) {
  89162. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  89163. }
  89164. return distance;
  89165. };
  89166. /**
  89167. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  89168. * is automatically returned to its default position (expected to be above ground plane).
  89169. */
  89170. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  89171. var _this = this;
  89172. if (this._elevationReturnTime < 0) {
  89173. return;
  89174. }
  89175. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  89176. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  89177. var limitBeta = Math.PI * 0.5;
  89178. // Bring the camera back up if below the ground plane
  89179. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  89180. this._betaIsAnimating = true;
  89181. //Transition to new position
  89182. this.stopAllAnimations();
  89183. if (!this._betaTransition) {
  89184. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89185. }
  89186. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  89187. _this._clearAnimationLocks();
  89188. _this.stopAllAnimations();
  89189. });
  89190. if (animatabe) {
  89191. this._animatables.push(animatabe);
  89192. }
  89193. }
  89194. };
  89195. /**
  89196. * Returns the frustum slope based on the canvas ratio and camera FOV
  89197. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  89198. */
  89199. FramingBehavior.prototype._getFrustumSlope = function () {
  89200. // Calculate the viewport ratio
  89201. // Aspect Ratio is Height/Width.
  89202. var camera = this._attachedCamera;
  89203. if (!camera) {
  89204. return BABYLON.Vector2.Zero();
  89205. }
  89206. var engine = camera.getScene().getEngine();
  89207. var aspectRatio = engine.getAspectRatio(camera);
  89208. // Camera FOV is the vertical field of view (top-bottom) in radians.
  89209. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  89210. var frustumSlopeY = Math.tan(camera.fov / 2);
  89211. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  89212. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  89213. // along the forward vector.
  89214. var frustumSlopeX = frustumSlopeY * aspectRatio;
  89215. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  89216. };
  89217. /**
  89218. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  89219. */
  89220. FramingBehavior.prototype._clearAnimationLocks = function () {
  89221. this._betaIsAnimating = false;
  89222. };
  89223. /**
  89224. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89225. */
  89226. FramingBehavior.prototype._applyUserInteraction = function () {
  89227. if (this.isUserIsMoving) {
  89228. this._lastInteractionTime = BABYLON.Tools.Now;
  89229. this.stopAllAnimations();
  89230. this._clearAnimationLocks();
  89231. }
  89232. };
  89233. /**
  89234. * Stops and removes all animations that have been applied to the camera
  89235. */
  89236. FramingBehavior.prototype.stopAllAnimations = function () {
  89237. if (this._attachedCamera) {
  89238. this._attachedCamera.animations = [];
  89239. }
  89240. while (this._animatables.length) {
  89241. if (this._animatables[0]) {
  89242. this._animatables[0].onAnimationEnd = null;
  89243. this._animatables[0].stop();
  89244. }
  89245. this._animatables.shift();
  89246. }
  89247. };
  89248. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  89249. /**
  89250. * Gets a value indicating if the user is moving the camera
  89251. */
  89252. get: function () {
  89253. if (!this._attachedCamera) {
  89254. return false;
  89255. }
  89256. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89257. this._attachedCamera.inertialBetaOffset !== 0 ||
  89258. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89259. this._attachedCamera.inertialPanningX !== 0 ||
  89260. this._attachedCamera.inertialPanningY !== 0 ||
  89261. this._isPointerDown;
  89262. },
  89263. enumerable: true,
  89264. configurable: true
  89265. });
  89266. /**
  89267. * The easing function used by animations
  89268. */
  89269. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  89270. /**
  89271. * The easing mode used by animations
  89272. */
  89273. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  89274. // Statics
  89275. /**
  89276. * The camera can move all the way towards the mesh.
  89277. */
  89278. FramingBehavior.IgnoreBoundsSizeMode = 0;
  89279. /**
  89280. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  89281. */
  89282. FramingBehavior.FitFrustumSidesMode = 1;
  89283. return FramingBehavior;
  89284. }());
  89285. BABYLON.FramingBehavior = FramingBehavior;
  89286. })(BABYLON || (BABYLON = {}));
  89287. //# sourceMappingURL=babylon.framingBehavior.js.map
  89288. "use strict";
  89289. var BABYLON;
  89290. (function (BABYLON) {
  89291. /**
  89292. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  89293. */
  89294. var BouncingBehavior = /** @class */ (function () {
  89295. function BouncingBehavior() {
  89296. /**
  89297. * The duration of the animation, in milliseconds
  89298. */
  89299. this.transitionDuration = 450;
  89300. /**
  89301. * Length of the distance animated by the transition when lower radius is reached
  89302. */
  89303. this.lowerRadiusTransitionRange = 2;
  89304. /**
  89305. * Length of the distance animated by the transition when upper radius is reached
  89306. */
  89307. this.upperRadiusTransitionRange = -2;
  89308. this._autoTransitionRange = false;
  89309. // Animations
  89310. this._radiusIsAnimating = false;
  89311. this._radiusBounceTransition = null;
  89312. this._animatables = new Array();
  89313. }
  89314. Object.defineProperty(BouncingBehavior.prototype, "name", {
  89315. get: function () {
  89316. return "Bouncing";
  89317. },
  89318. enumerable: true,
  89319. configurable: true
  89320. });
  89321. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  89322. /**
  89323. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89324. */
  89325. get: function () {
  89326. return this._autoTransitionRange;
  89327. },
  89328. /**
  89329. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89330. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  89331. */
  89332. set: function (value) {
  89333. var _this = this;
  89334. if (this._autoTransitionRange === value) {
  89335. return;
  89336. }
  89337. this._autoTransitionRange = value;
  89338. var camera = this._attachedCamera;
  89339. if (!camera) {
  89340. return;
  89341. }
  89342. if (value) {
  89343. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89344. if (!mesh) {
  89345. return;
  89346. }
  89347. mesh.computeWorldMatrix(true);
  89348. var diagonal = mesh.getBoundingInfo().diagonalLength;
  89349. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  89350. _this.upperRadiusTransitionRange = diagonal * 0.05;
  89351. });
  89352. }
  89353. else if (this._onMeshTargetChangedObserver) {
  89354. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89355. }
  89356. },
  89357. enumerable: true,
  89358. configurable: true
  89359. });
  89360. BouncingBehavior.prototype.init = function () {
  89361. // Do notihng
  89362. };
  89363. BouncingBehavior.prototype.attach = function (camera) {
  89364. var _this = this;
  89365. this._attachedCamera = camera;
  89366. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89367. if (!_this._attachedCamera) {
  89368. return;
  89369. }
  89370. // Add the bounce animation to the lower radius limit
  89371. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  89372. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  89373. }
  89374. // Add the bounce animation to the upper radius limit
  89375. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  89376. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  89377. }
  89378. });
  89379. };
  89380. BouncingBehavior.prototype.detach = function () {
  89381. if (!this._attachedCamera) {
  89382. return;
  89383. }
  89384. if (this._onAfterCheckInputsObserver) {
  89385. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89386. }
  89387. if (this._onMeshTargetChangedObserver) {
  89388. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89389. }
  89390. this._attachedCamera = null;
  89391. };
  89392. /**
  89393. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  89394. * @param radiusLimit The limit to check against.
  89395. * @return Bool to indicate if at limit.
  89396. */
  89397. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  89398. if (!this._attachedCamera) {
  89399. return false;
  89400. }
  89401. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  89402. return true;
  89403. }
  89404. return false;
  89405. };
  89406. /**
  89407. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  89408. * @param radiusDelta The delta by which to animate to. Can be negative.
  89409. */
  89410. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  89411. var _this = this;
  89412. if (!this._attachedCamera) {
  89413. return;
  89414. }
  89415. if (!this._radiusBounceTransition) {
  89416. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  89417. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  89418. }
  89419. // Prevent zoom until bounce has completed
  89420. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  89421. this._attachedCamera.wheelPrecision = Infinity;
  89422. this._attachedCamera.inertialRadiusOffset = 0;
  89423. // Animate to the radius limit
  89424. this.stopAllAnimations();
  89425. this._radiusIsAnimating = true;
  89426. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  89427. if (animatable) {
  89428. this._animatables.push(animatable);
  89429. }
  89430. };
  89431. /**
  89432. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  89433. */
  89434. BouncingBehavior.prototype._clearAnimationLocks = function () {
  89435. this._radiusIsAnimating = false;
  89436. if (this._attachedCamera) {
  89437. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  89438. }
  89439. };
  89440. /**
  89441. * Stops and removes all animations that have been applied to the camera
  89442. */
  89443. BouncingBehavior.prototype.stopAllAnimations = function () {
  89444. if (this._attachedCamera) {
  89445. this._attachedCamera.animations = [];
  89446. }
  89447. while (this._animatables.length) {
  89448. this._animatables[0].onAnimationEnd = null;
  89449. this._animatables[0].stop();
  89450. this._animatables.shift();
  89451. }
  89452. };
  89453. /**
  89454. * The easing function used by animations
  89455. */
  89456. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  89457. /**
  89458. * The easing mode used by animations
  89459. */
  89460. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  89461. return BouncingBehavior;
  89462. }());
  89463. BABYLON.BouncingBehavior = BouncingBehavior;
  89464. })(BABYLON || (BABYLON = {}));
  89465. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  89466. "use strict";
  89467. var BABYLON;
  89468. (function (BABYLON) {
  89469. var AutoRotationBehavior = /** @class */ (function () {
  89470. function AutoRotationBehavior() {
  89471. this._zoomStopsAnimation = false;
  89472. this._idleRotationSpeed = 0.05;
  89473. this._idleRotationWaitTime = 2000;
  89474. this._idleRotationSpinupTime = 2000;
  89475. this._isPointerDown = false;
  89476. this._lastFrameTime = null;
  89477. this._lastInteractionTime = -Infinity;
  89478. this._cameraRotationSpeed = 0;
  89479. this._lastFrameRadius = 0;
  89480. }
  89481. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  89482. get: function () {
  89483. return "AutoRotation";
  89484. },
  89485. enumerable: true,
  89486. configurable: true
  89487. });
  89488. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  89489. /**
  89490. * Gets the flag that indicates if user zooming should stop animation.
  89491. */
  89492. get: function () {
  89493. return this._zoomStopsAnimation;
  89494. },
  89495. /**
  89496. * Sets the flag that indicates if user zooming should stop animation.
  89497. */
  89498. set: function (flag) {
  89499. this._zoomStopsAnimation = flag;
  89500. },
  89501. enumerable: true,
  89502. configurable: true
  89503. });
  89504. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  89505. /**
  89506. * Gets the default speed at which the camera rotates around the model.
  89507. */
  89508. get: function () {
  89509. return this._idleRotationSpeed;
  89510. },
  89511. /**
  89512. * Sets the default speed at which the camera rotates around the model.
  89513. */
  89514. set: function (speed) {
  89515. this._idleRotationSpeed = speed;
  89516. },
  89517. enumerable: true,
  89518. configurable: true
  89519. });
  89520. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  89521. /**
  89522. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  89523. */
  89524. get: function () {
  89525. return this._idleRotationWaitTime;
  89526. },
  89527. /**
  89528. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  89529. */
  89530. set: function (time) {
  89531. this._idleRotationWaitTime = time;
  89532. },
  89533. enumerable: true,
  89534. configurable: true
  89535. });
  89536. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  89537. /**
  89538. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89539. */
  89540. get: function () {
  89541. return this._idleRotationSpinupTime;
  89542. },
  89543. /**
  89544. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89545. */
  89546. set: function (time) {
  89547. this._idleRotationSpinupTime = time;
  89548. },
  89549. enumerable: true,
  89550. configurable: true
  89551. });
  89552. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  89553. /**
  89554. * Gets a value indicating if the camera is currently rotating because of this behavior
  89555. */
  89556. get: function () {
  89557. return Math.abs(this._cameraRotationSpeed) > 0;
  89558. },
  89559. enumerable: true,
  89560. configurable: true
  89561. });
  89562. AutoRotationBehavior.prototype.init = function () {
  89563. // Do notihng
  89564. };
  89565. AutoRotationBehavior.prototype.attach = function (camera) {
  89566. var _this = this;
  89567. this._attachedCamera = camera;
  89568. var scene = this._attachedCamera.getScene();
  89569. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89570. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89571. _this._isPointerDown = true;
  89572. return;
  89573. }
  89574. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89575. _this._isPointerDown = false;
  89576. }
  89577. });
  89578. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89579. var now = BABYLON.Tools.Now;
  89580. var dt = 0;
  89581. if (_this._lastFrameTime != null) {
  89582. dt = now - _this._lastFrameTime;
  89583. }
  89584. _this._lastFrameTime = now;
  89585. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89586. _this._applyUserInteraction();
  89587. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  89588. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  89589. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  89590. // Step camera rotation by rotation speed
  89591. if (_this._attachedCamera) {
  89592. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  89593. }
  89594. });
  89595. };
  89596. AutoRotationBehavior.prototype.detach = function () {
  89597. if (!this._attachedCamera) {
  89598. return;
  89599. }
  89600. var scene = this._attachedCamera.getScene();
  89601. if (this._onPrePointerObservableObserver) {
  89602. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89603. }
  89604. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89605. this._attachedCamera = null;
  89606. };
  89607. /**
  89608. * Returns true if user is scrolling.
  89609. * @return true if user is scrolling.
  89610. */
  89611. AutoRotationBehavior.prototype._userIsZooming = function () {
  89612. if (!this._attachedCamera) {
  89613. return false;
  89614. }
  89615. return this._attachedCamera.inertialRadiusOffset !== 0;
  89616. };
  89617. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  89618. if (!this._attachedCamera) {
  89619. return false;
  89620. }
  89621. var zoomHasHitLimit = false;
  89622. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  89623. zoomHasHitLimit = true;
  89624. }
  89625. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  89626. this._lastFrameRadius = this._attachedCamera.radius;
  89627. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  89628. };
  89629. /**
  89630. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89631. */
  89632. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  89633. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  89634. this._lastInteractionTime = BABYLON.Tools.Now;
  89635. }
  89636. };
  89637. // Tools
  89638. AutoRotationBehavior.prototype._userIsMoving = function () {
  89639. if (!this._attachedCamera) {
  89640. return false;
  89641. }
  89642. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89643. this._attachedCamera.inertialBetaOffset !== 0 ||
  89644. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89645. this._attachedCamera.inertialPanningX !== 0 ||
  89646. this._attachedCamera.inertialPanningY !== 0 ||
  89647. this._isPointerDown;
  89648. };
  89649. return AutoRotationBehavior;
  89650. }());
  89651. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  89652. })(BABYLON || (BABYLON = {}));
  89653. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  89654. "use strict";
  89655. var BABYLON;
  89656. (function (BABYLON) {
  89657. var NullEngineOptions = /** @class */ (function () {
  89658. function NullEngineOptions() {
  89659. this.renderWidth = 512;
  89660. this.renderHeight = 256;
  89661. this.textureSize = 512;
  89662. this.deterministicLockstep = false;
  89663. this.lockstepMaxSteps = 4;
  89664. }
  89665. return NullEngineOptions;
  89666. }());
  89667. BABYLON.NullEngineOptions = NullEngineOptions;
  89668. /**
  89669. * The null engine class provides support for headless version of babylon.js.
  89670. * This can be used in server side scenario or for testing purposes
  89671. */
  89672. var NullEngine = /** @class */ (function (_super) {
  89673. __extends(NullEngine, _super);
  89674. function NullEngine(options) {
  89675. if (options === void 0) { options = new NullEngineOptions(); }
  89676. var _this = _super.call(this, null) || this;
  89677. if (options.deterministicLockstep === undefined) {
  89678. options.deterministicLockstep = false;
  89679. }
  89680. if (options.lockstepMaxSteps === undefined) {
  89681. options.lockstepMaxSteps = 4;
  89682. }
  89683. _this._options = options;
  89684. // Init caps
  89685. // We consider we are on a webgl1 capable device
  89686. _this._caps = new BABYLON.EngineCapabilities();
  89687. _this._caps.maxTexturesImageUnits = 16;
  89688. _this._caps.maxVertexTextureImageUnits = 16;
  89689. _this._caps.maxTextureSize = 512;
  89690. _this._caps.maxCubemapTextureSize = 512;
  89691. _this._caps.maxRenderTextureSize = 512;
  89692. _this._caps.maxVertexAttribs = 16;
  89693. _this._caps.maxVaryingVectors = 16;
  89694. _this._caps.maxFragmentUniformVectors = 16;
  89695. _this._caps.maxVertexUniformVectors = 16;
  89696. // Extensions
  89697. _this._caps.standardDerivatives = false;
  89698. _this._caps.astc = null;
  89699. _this._caps.s3tc = null;
  89700. _this._caps.pvrtc = null;
  89701. _this._caps.etc1 = null;
  89702. _this._caps.etc2 = null;
  89703. _this._caps.textureAnisotropicFilterExtension = null;
  89704. _this._caps.maxAnisotropy = 0;
  89705. _this._caps.uintIndices = false;
  89706. _this._caps.fragmentDepthSupported = false;
  89707. _this._caps.highPrecisionShaderSupported = true;
  89708. _this._caps.colorBufferFloat = false;
  89709. _this._caps.textureFloat = false;
  89710. _this._caps.textureFloatLinearFiltering = false;
  89711. _this._caps.textureFloatRender = false;
  89712. _this._caps.textureHalfFloat = false;
  89713. _this._caps.textureHalfFloatLinearFiltering = false;
  89714. _this._caps.textureHalfFloatRender = false;
  89715. _this._caps.textureLOD = false;
  89716. _this._caps.drawBuffersExtension = false;
  89717. _this._caps.depthTextureExtension = false;
  89718. _this._caps.vertexArrayObject = false;
  89719. _this._caps.instancedArrays = false;
  89720. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  89721. // Wrappers
  89722. if (typeof URL === "undefined") {
  89723. URL = {
  89724. createObjectURL: function () { },
  89725. revokeObjectURL: function () { }
  89726. };
  89727. }
  89728. if (typeof Blob === "undefined") {
  89729. Blob = function () { };
  89730. }
  89731. return _this;
  89732. }
  89733. NullEngine.prototype.isDeterministicLockStep = function () {
  89734. return this._options.deterministicLockstep;
  89735. };
  89736. NullEngine.prototype.getLockstepMaxSteps = function () {
  89737. return this._options.lockstepMaxSteps;
  89738. };
  89739. NullEngine.prototype.getHardwareScalingLevel = function () {
  89740. return 1.0;
  89741. };
  89742. NullEngine.prototype.createVertexBuffer = function (vertices) {
  89743. return {
  89744. capacity: 0,
  89745. references: 1,
  89746. is32Bits: false
  89747. };
  89748. };
  89749. NullEngine.prototype.createIndexBuffer = function (indices) {
  89750. return {
  89751. capacity: 0,
  89752. references: 1,
  89753. is32Bits: false
  89754. };
  89755. };
  89756. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  89757. if (stencil === void 0) { stencil = false; }
  89758. };
  89759. NullEngine.prototype.getRenderWidth = function (useScreen) {
  89760. if (useScreen === void 0) { useScreen = false; }
  89761. if (!useScreen && this._currentRenderTarget) {
  89762. return this._currentRenderTarget.width;
  89763. }
  89764. return this._options.renderWidth;
  89765. };
  89766. NullEngine.prototype.getRenderHeight = function (useScreen) {
  89767. if (useScreen === void 0) { useScreen = false; }
  89768. if (!useScreen && this._currentRenderTarget) {
  89769. return this._currentRenderTarget.height;
  89770. }
  89771. return this._options.renderHeight;
  89772. };
  89773. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  89774. this._cachedViewport = viewport;
  89775. };
  89776. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  89777. return {
  89778. transformFeedback: null,
  89779. __SPECTOR_rebuildProgram: null
  89780. };
  89781. };
  89782. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  89783. return [];
  89784. };
  89785. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  89786. return [];
  89787. };
  89788. NullEngine.prototype.bindSamplers = function (effect) {
  89789. this._currentEffect = null;
  89790. };
  89791. NullEngine.prototype.enableEffect = function (effect) {
  89792. this._currentEffect = effect;
  89793. if (effect.onBind) {
  89794. effect.onBind(effect);
  89795. }
  89796. effect.onBindObservable.notifyObservers(effect);
  89797. };
  89798. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  89799. if (zOffset === void 0) { zOffset = 0; }
  89800. if (reverseSide === void 0) { reverseSide = false; }
  89801. };
  89802. NullEngine.prototype.setIntArray = function (uniform, array) {
  89803. };
  89804. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  89805. };
  89806. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  89807. };
  89808. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  89809. };
  89810. NullEngine.prototype.setFloatArray = function (uniform, array) {
  89811. };
  89812. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  89813. };
  89814. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  89815. };
  89816. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  89817. };
  89818. NullEngine.prototype.setArray = function (uniform, array) {
  89819. };
  89820. NullEngine.prototype.setArray2 = function (uniform, array) {
  89821. };
  89822. NullEngine.prototype.setArray3 = function (uniform, array) {
  89823. };
  89824. NullEngine.prototype.setArray4 = function (uniform, array) {
  89825. };
  89826. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  89827. };
  89828. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  89829. };
  89830. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  89831. };
  89832. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  89833. };
  89834. NullEngine.prototype.setFloat = function (uniform, value) {
  89835. };
  89836. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  89837. };
  89838. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  89839. };
  89840. NullEngine.prototype.setBool = function (uniform, bool) {
  89841. };
  89842. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  89843. };
  89844. NullEngine.prototype.setColor3 = function (uniform, color3) {
  89845. };
  89846. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  89847. };
  89848. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  89849. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  89850. if (this._alphaMode === mode) {
  89851. return;
  89852. }
  89853. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  89854. if (!noDepthWriteChange) {
  89855. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  89856. }
  89857. this._alphaMode = mode;
  89858. };
  89859. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  89860. };
  89861. NullEngine.prototype.wipeCaches = function (bruteForce) {
  89862. if (this.preventCacheWipeBetweenFrames) {
  89863. return;
  89864. }
  89865. this.resetTextureCache();
  89866. this._currentEffect = null;
  89867. if (bruteForce) {
  89868. this._currentProgram = null;
  89869. this._stencilState.reset();
  89870. this._depthCullingState.reset();
  89871. this._alphaState.reset();
  89872. }
  89873. this._cachedVertexBuffers = null;
  89874. this._cachedIndexBuffer = null;
  89875. this._cachedEffectForVertexBuffers = null;
  89876. };
  89877. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  89878. };
  89879. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  89880. };
  89881. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  89882. };
  89883. NullEngine.prototype._createTexture = function () {
  89884. return {};
  89885. };
  89886. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  89887. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  89888. if (onLoad === void 0) { onLoad = null; }
  89889. if (onError === void 0) { onError = null; }
  89890. if (buffer === void 0) { buffer = null; }
  89891. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  89892. var url = String(urlArg);
  89893. texture.url = url;
  89894. texture.generateMipMaps = !noMipmap;
  89895. texture.samplingMode = samplingMode;
  89896. texture.invertY = invertY;
  89897. texture.baseWidth = this._options.textureSize;
  89898. texture.baseHeight = this._options.textureSize;
  89899. texture.width = this._options.textureSize;
  89900. texture.height = this._options.textureSize;
  89901. if (format) {
  89902. texture.format = format;
  89903. }
  89904. texture.isReady = true;
  89905. if (onLoad) {
  89906. onLoad();
  89907. }
  89908. return texture;
  89909. };
  89910. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  89911. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  89912. if (options !== undefined && typeof options === "object") {
  89913. fullOptions.generateMipMaps = options.generateMipMaps;
  89914. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  89915. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  89916. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  89917. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  89918. }
  89919. else {
  89920. fullOptions.generateMipMaps = options;
  89921. fullOptions.generateDepthBuffer = true;
  89922. fullOptions.generateStencilBuffer = false;
  89923. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89924. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  89925. }
  89926. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  89927. var width = size.width || size;
  89928. var height = size.height || size;
  89929. texture._depthStencilBuffer = {};
  89930. texture._framebuffer = {};
  89931. texture.baseWidth = width;
  89932. texture.baseHeight = height;
  89933. texture.width = width;
  89934. texture.height = height;
  89935. texture.isReady = true;
  89936. texture.samples = 1;
  89937. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  89938. texture.samplingMode = fullOptions.samplingMode;
  89939. texture.type = fullOptions.type;
  89940. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  89941. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  89942. return texture;
  89943. };
  89944. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  89945. texture.samplingMode = samplingMode;
  89946. };
  89947. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  89948. if (this._currentRenderTarget) {
  89949. this.unBindFramebuffer(this._currentRenderTarget);
  89950. }
  89951. this._currentRenderTarget = texture;
  89952. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  89953. if (this._cachedViewport && !forceFullscreenViewport) {
  89954. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  89955. }
  89956. };
  89957. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  89958. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  89959. this._currentRenderTarget = null;
  89960. if (onBeforeUnbind) {
  89961. if (texture._MSAAFramebuffer) {
  89962. this._currentFramebuffer = texture._framebuffer;
  89963. }
  89964. onBeforeUnbind();
  89965. }
  89966. this._currentFramebuffer = null;
  89967. };
  89968. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  89969. var vbo = {
  89970. capacity: 1,
  89971. references: 1,
  89972. is32Bits: false
  89973. };
  89974. return vbo;
  89975. };
  89976. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  89977. if (offset === void 0) { offset = 0; }
  89978. };
  89979. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  89980. };
  89981. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  89982. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  89983. this._boundTexturesCache[this._activeChannel] = texture;
  89984. }
  89985. };
  89986. NullEngine.prototype._bindTexture = function (channel, texture) {
  89987. if (channel < 0) {
  89988. return;
  89989. }
  89990. this._bindTextureDirectly(0, texture);
  89991. };
  89992. NullEngine.prototype._releaseBuffer = function (buffer) {
  89993. buffer.references--;
  89994. if (buffer.references === 0) {
  89995. return true;
  89996. }
  89997. return false;
  89998. };
  89999. return NullEngine;
  90000. }(BABYLON.Engine));
  90001. BABYLON.NullEngine = NullEngine;
  90002. })(BABYLON || (BABYLON = {}));
  90003. //# sourceMappingURL=babylon.nullEngine.js.map
  90004. "use strict";
  90005. var BABYLON;
  90006. (function (BABYLON) {
  90007. /**
  90008. * This class can be used to get instrumentation data from a Babylon engine
  90009. */
  90010. var EngineInstrumentation = /** @class */ (function () {
  90011. function EngineInstrumentation(engine) {
  90012. this.engine = engine;
  90013. this._captureGPUFrameTime = false;
  90014. this._gpuFrameTime = new BABYLON.PerfCounter();
  90015. this._captureShaderCompilationTime = false;
  90016. this._shaderCompilationTime = new BABYLON.PerfCounter();
  90017. // Observers
  90018. this._onBeginFrameObserver = null;
  90019. this._onEndFrameObserver = null;
  90020. this._onBeforeShaderCompilationObserver = null;
  90021. this._onAfterShaderCompilationObserver = null;
  90022. }
  90023. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  90024. // Properties
  90025. /**
  90026. * Gets the perf counter used for GPU frame time
  90027. */
  90028. get: function () {
  90029. return this._gpuFrameTime;
  90030. },
  90031. enumerable: true,
  90032. configurable: true
  90033. });
  90034. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  90035. /**
  90036. * Gets the GPU frame time capture status
  90037. */
  90038. get: function () {
  90039. return this._captureGPUFrameTime;
  90040. },
  90041. /**
  90042. * Enable or disable the GPU frame time capture
  90043. */
  90044. set: function (value) {
  90045. var _this = this;
  90046. if (value === this._captureGPUFrameTime) {
  90047. return;
  90048. }
  90049. this._captureGPUFrameTime = value;
  90050. if (value) {
  90051. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  90052. if (!_this._gpuFrameTimeToken) {
  90053. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  90054. }
  90055. });
  90056. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  90057. if (!_this._gpuFrameTimeToken) {
  90058. return;
  90059. }
  90060. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  90061. if (time > -1) {
  90062. _this._gpuFrameTimeToken = null;
  90063. _this._gpuFrameTime.fetchNewFrame();
  90064. _this._gpuFrameTime.addCount(time, true);
  90065. }
  90066. });
  90067. }
  90068. else {
  90069. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90070. this._onBeginFrameObserver = null;
  90071. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90072. this._onEndFrameObserver = null;
  90073. }
  90074. },
  90075. enumerable: true,
  90076. configurable: true
  90077. });
  90078. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  90079. /**
  90080. * Gets the perf counter used for shader compilation time
  90081. */
  90082. get: function () {
  90083. return this._shaderCompilationTime;
  90084. },
  90085. enumerable: true,
  90086. configurable: true
  90087. });
  90088. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  90089. /**
  90090. * Gets the shader compilation time capture status
  90091. */
  90092. get: function () {
  90093. return this._captureShaderCompilationTime;
  90094. },
  90095. /**
  90096. * Enable or disable the shader compilation time capture
  90097. */
  90098. set: function (value) {
  90099. var _this = this;
  90100. if (value === this._captureShaderCompilationTime) {
  90101. return;
  90102. }
  90103. this._captureShaderCompilationTime = value;
  90104. if (value) {
  90105. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  90106. _this._shaderCompilationTime.fetchNewFrame();
  90107. _this._shaderCompilationTime.beginMonitoring();
  90108. });
  90109. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  90110. _this._shaderCompilationTime.endMonitoring();
  90111. });
  90112. }
  90113. else {
  90114. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90115. this._onBeforeShaderCompilationObserver = null;
  90116. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90117. this._onAfterShaderCompilationObserver = null;
  90118. }
  90119. },
  90120. enumerable: true,
  90121. configurable: true
  90122. });
  90123. EngineInstrumentation.prototype.dispose = function () {
  90124. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90125. this._onBeginFrameObserver = null;
  90126. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90127. this._onEndFrameObserver = null;
  90128. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90129. this._onBeforeShaderCompilationObserver = null;
  90130. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90131. this._onAfterShaderCompilationObserver = null;
  90132. this.engine = null;
  90133. };
  90134. return EngineInstrumentation;
  90135. }());
  90136. BABYLON.EngineInstrumentation = EngineInstrumentation;
  90137. })(BABYLON || (BABYLON = {}));
  90138. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  90139. "use strict";
  90140. var BABYLON;
  90141. (function (BABYLON) {
  90142. /**
  90143. * This class can be used to get instrumentation data from a Babylon engine
  90144. */
  90145. var SceneInstrumentation = /** @class */ (function () {
  90146. function SceneInstrumentation(scene) {
  90147. var _this = this;
  90148. this.scene = scene;
  90149. this._captureActiveMeshesEvaluationTime = false;
  90150. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  90151. this._captureRenderTargetsRenderTime = false;
  90152. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  90153. this._captureFrameTime = false;
  90154. this._frameTime = new BABYLON.PerfCounter();
  90155. this._captureRenderTime = false;
  90156. this._renderTime = new BABYLON.PerfCounter();
  90157. this._captureInterFrameTime = false;
  90158. this._interFrameTime = new BABYLON.PerfCounter();
  90159. this._captureParticlesRenderTime = false;
  90160. this._particlesRenderTime = new BABYLON.PerfCounter();
  90161. this._captureSpritesRenderTime = false;
  90162. this._spritesRenderTime = new BABYLON.PerfCounter();
  90163. this._capturePhysicsTime = false;
  90164. this._physicsTime = new BABYLON.PerfCounter();
  90165. this._captureAnimationsTime = false;
  90166. this._animationsTime = new BABYLON.PerfCounter();
  90167. // Observers
  90168. this._onBeforeActiveMeshesEvaluationObserver = null;
  90169. this._onAfterActiveMeshesEvaluationObserver = null;
  90170. this._onBeforeRenderTargetsRenderObserver = null;
  90171. this._onAfterRenderTargetsRenderObserver = null;
  90172. this._onAfterRenderObserver = null;
  90173. this._onBeforeDrawPhaseObserver = null;
  90174. this._onAfterDrawPhaseObserver = null;
  90175. this._onBeforeAnimationsObserver = null;
  90176. this._onBeforeParticlesRenderingObserver = null;
  90177. this._onAfterParticlesRenderingObserver = null;
  90178. this._onBeforeSpritesRenderingObserver = null;
  90179. this._onAfterSpritesRenderingObserver = null;
  90180. this._onBeforePhysicsObserver = null;
  90181. this._onAfterPhysicsObserver = null;
  90182. this._onAfterAnimationsObserver = null;
  90183. // Before render
  90184. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  90185. if (_this._captureActiveMeshesEvaluationTime) {
  90186. _this._activeMeshesEvaluationTime.fetchNewFrame();
  90187. }
  90188. if (_this._captureRenderTargetsRenderTime) {
  90189. _this._renderTargetsRenderTime.fetchNewFrame();
  90190. }
  90191. if (_this._captureFrameTime) {
  90192. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  90193. _this._frameTime.beginMonitoring();
  90194. }
  90195. if (_this._captureInterFrameTime) {
  90196. _this._interFrameTime.endMonitoring();
  90197. }
  90198. if (_this._captureParticlesRenderTime) {
  90199. _this._particlesRenderTime.fetchNewFrame();
  90200. }
  90201. if (_this._captureSpritesRenderTime) {
  90202. _this._spritesRenderTime.fetchNewFrame();
  90203. }
  90204. if (_this._captureAnimationsTime) {
  90205. _this._animationsTime.beginMonitoring();
  90206. }
  90207. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  90208. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  90209. });
  90210. // After render
  90211. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  90212. if (_this._captureFrameTime) {
  90213. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  90214. _this._frameTime.endMonitoring();
  90215. }
  90216. if (_this._captureRenderTime) {
  90217. _this._renderTime.endMonitoring(false);
  90218. }
  90219. if (_this._captureInterFrameTime) {
  90220. _this._interFrameTime.beginMonitoring();
  90221. }
  90222. });
  90223. }
  90224. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  90225. // Properties
  90226. /**
  90227. * Gets the perf counter used for active meshes evaluation time
  90228. */
  90229. get: function () {
  90230. return this._activeMeshesEvaluationTime;
  90231. },
  90232. enumerable: true,
  90233. configurable: true
  90234. });
  90235. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  90236. /**
  90237. * Gets the active meshes evaluation time capture status
  90238. */
  90239. get: function () {
  90240. return this._captureActiveMeshesEvaluationTime;
  90241. },
  90242. /**
  90243. * Enable or disable the active meshes evaluation time capture
  90244. */
  90245. set: function (value) {
  90246. var _this = this;
  90247. if (value === this._captureActiveMeshesEvaluationTime) {
  90248. return;
  90249. }
  90250. this._captureActiveMeshesEvaluationTime = value;
  90251. if (value) {
  90252. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  90253. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  90254. _this._activeMeshesEvaluationTime.beginMonitoring();
  90255. });
  90256. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  90257. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  90258. _this._activeMeshesEvaluationTime.endMonitoring();
  90259. });
  90260. }
  90261. else {
  90262. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90263. this._onBeforeActiveMeshesEvaluationObserver = null;
  90264. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90265. this._onAfterActiveMeshesEvaluationObserver = null;
  90266. }
  90267. },
  90268. enumerable: true,
  90269. configurable: true
  90270. });
  90271. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  90272. /**
  90273. * Gets the perf counter used for render targets render time
  90274. */
  90275. get: function () {
  90276. return this._renderTargetsRenderTime;
  90277. },
  90278. enumerable: true,
  90279. configurable: true
  90280. });
  90281. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  90282. /**
  90283. * Gets the render targets render time capture status
  90284. */
  90285. get: function () {
  90286. return this._captureRenderTargetsRenderTime;
  90287. },
  90288. /**
  90289. * Enable or disable the render targets render time capture
  90290. */
  90291. set: function (value) {
  90292. var _this = this;
  90293. if (value === this._captureRenderTargetsRenderTime) {
  90294. return;
  90295. }
  90296. this._captureRenderTargetsRenderTime = value;
  90297. if (value) {
  90298. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  90299. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  90300. _this._renderTargetsRenderTime.beginMonitoring();
  90301. });
  90302. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  90303. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  90304. _this._renderTargetsRenderTime.endMonitoring(false);
  90305. });
  90306. }
  90307. else {
  90308. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90309. this._onBeforeRenderTargetsRenderObserver = null;
  90310. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90311. this._onAfterRenderTargetsRenderObserver = null;
  90312. }
  90313. },
  90314. enumerable: true,
  90315. configurable: true
  90316. });
  90317. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  90318. /**
  90319. * Gets the perf counter used for particles render time
  90320. */
  90321. get: function () {
  90322. return this._particlesRenderTime;
  90323. },
  90324. enumerable: true,
  90325. configurable: true
  90326. });
  90327. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  90328. /**
  90329. * Gets the particles render time capture status
  90330. */
  90331. get: function () {
  90332. return this._captureParticlesRenderTime;
  90333. },
  90334. /**
  90335. * Enable or disable the particles render time capture
  90336. */
  90337. set: function (value) {
  90338. var _this = this;
  90339. if (value === this._captureParticlesRenderTime) {
  90340. return;
  90341. }
  90342. this._captureParticlesRenderTime = value;
  90343. if (value) {
  90344. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  90345. BABYLON.Tools.StartPerformanceCounter("Particles");
  90346. _this._particlesRenderTime.beginMonitoring();
  90347. });
  90348. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  90349. BABYLON.Tools.EndPerformanceCounter("Particles");
  90350. _this._particlesRenderTime.endMonitoring(false);
  90351. });
  90352. }
  90353. else {
  90354. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90355. this._onBeforeParticlesRenderingObserver = null;
  90356. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90357. this._onAfterParticlesRenderingObserver = null;
  90358. }
  90359. },
  90360. enumerable: true,
  90361. configurable: true
  90362. });
  90363. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  90364. /**
  90365. * Gets the perf counter used for sprites render time
  90366. */
  90367. get: function () {
  90368. return this._spritesRenderTime;
  90369. },
  90370. enumerable: true,
  90371. configurable: true
  90372. });
  90373. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  90374. /**
  90375. * Gets the sprites render time capture status
  90376. */
  90377. get: function () {
  90378. return this._captureSpritesRenderTime;
  90379. },
  90380. /**
  90381. * Enable or disable the sprites render time capture
  90382. */
  90383. set: function (value) {
  90384. var _this = this;
  90385. if (value === this._captureSpritesRenderTime) {
  90386. return;
  90387. }
  90388. this._captureSpritesRenderTime = value;
  90389. if (value) {
  90390. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  90391. BABYLON.Tools.StartPerformanceCounter("Sprites");
  90392. _this._spritesRenderTime.beginMonitoring();
  90393. });
  90394. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  90395. BABYLON.Tools.EndPerformanceCounter("Sprites");
  90396. _this._spritesRenderTime.endMonitoring(false);
  90397. });
  90398. }
  90399. else {
  90400. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90401. this._onBeforeSpritesRenderingObserver = null;
  90402. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90403. this._onAfterSpritesRenderingObserver = null;
  90404. }
  90405. },
  90406. enumerable: true,
  90407. configurable: true
  90408. });
  90409. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  90410. /**
  90411. * Gets the perf counter used for physics time
  90412. */
  90413. get: function () {
  90414. return this._physicsTime;
  90415. },
  90416. enumerable: true,
  90417. configurable: true
  90418. });
  90419. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  90420. /**
  90421. * Gets the physics time capture status
  90422. */
  90423. get: function () {
  90424. return this._capturePhysicsTime;
  90425. },
  90426. /**
  90427. * Enable or disable the physics time capture
  90428. */
  90429. set: function (value) {
  90430. var _this = this;
  90431. if (value === this._capturePhysicsTime) {
  90432. return;
  90433. }
  90434. this._capturePhysicsTime = value;
  90435. if (value) {
  90436. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  90437. BABYLON.Tools.StartPerformanceCounter("Physics");
  90438. _this._physicsTime.beginMonitoring();
  90439. });
  90440. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  90441. BABYLON.Tools.EndPerformanceCounter("Physics");
  90442. _this._physicsTime.endMonitoring();
  90443. });
  90444. }
  90445. else {
  90446. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90447. this._onBeforePhysicsObserver = null;
  90448. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90449. this._onAfterPhysicsObserver = null;
  90450. }
  90451. },
  90452. enumerable: true,
  90453. configurable: true
  90454. });
  90455. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  90456. /**
  90457. * Gets the perf counter used for animations time
  90458. */
  90459. get: function () {
  90460. return this._animationsTime;
  90461. },
  90462. enumerable: true,
  90463. configurable: true
  90464. });
  90465. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  90466. /**
  90467. * Gets the animations time capture status
  90468. */
  90469. get: function () {
  90470. return this._captureAnimationsTime;
  90471. },
  90472. /**
  90473. * Enable or disable the animations time capture
  90474. */
  90475. set: function (value) {
  90476. var _this = this;
  90477. if (value === this._captureAnimationsTime) {
  90478. return;
  90479. }
  90480. this._captureAnimationsTime = value;
  90481. if (value) {
  90482. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  90483. _this._animationsTime.endMonitoring();
  90484. });
  90485. }
  90486. else {
  90487. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90488. this._onAfterAnimationsObserver = null;
  90489. }
  90490. },
  90491. enumerable: true,
  90492. configurable: true
  90493. });
  90494. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  90495. /**
  90496. * Gets the perf counter used for frame time capture
  90497. */
  90498. get: function () {
  90499. return this._frameTime;
  90500. },
  90501. enumerable: true,
  90502. configurable: true
  90503. });
  90504. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  90505. /**
  90506. * Gets the frame time capture status
  90507. */
  90508. get: function () {
  90509. return this._captureFrameTime;
  90510. },
  90511. /**
  90512. * Enable or disable the frame time capture
  90513. */
  90514. set: function (value) {
  90515. this._captureFrameTime = value;
  90516. },
  90517. enumerable: true,
  90518. configurable: true
  90519. });
  90520. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  90521. /**
  90522. * Gets the perf counter used for inter-frames time capture
  90523. */
  90524. get: function () {
  90525. return this._interFrameTime;
  90526. },
  90527. enumerable: true,
  90528. configurable: true
  90529. });
  90530. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  90531. /**
  90532. * Gets the inter-frames time capture status
  90533. */
  90534. get: function () {
  90535. return this._captureInterFrameTime;
  90536. },
  90537. /**
  90538. * Enable or disable the inter-frames time capture
  90539. */
  90540. set: function (value) {
  90541. this._captureInterFrameTime = value;
  90542. },
  90543. enumerable: true,
  90544. configurable: true
  90545. });
  90546. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  90547. /**
  90548. * Gets the perf counter used for render time capture
  90549. */
  90550. get: function () {
  90551. return this._renderTime;
  90552. },
  90553. enumerable: true,
  90554. configurable: true
  90555. });
  90556. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  90557. /**
  90558. * Gets the render time capture status
  90559. */
  90560. get: function () {
  90561. return this._captureRenderTime;
  90562. },
  90563. /**
  90564. * Enable or disable the render time capture
  90565. */
  90566. set: function (value) {
  90567. var _this = this;
  90568. if (value === this._captureRenderTime) {
  90569. return;
  90570. }
  90571. this._captureRenderTime = value;
  90572. if (value) {
  90573. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  90574. _this._renderTime.beginMonitoring();
  90575. BABYLON.Tools.StartPerformanceCounter("Main render");
  90576. });
  90577. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  90578. _this._renderTime.endMonitoring(false);
  90579. BABYLON.Tools.EndPerformanceCounter("Main render");
  90580. });
  90581. }
  90582. else {
  90583. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90584. this._onBeforeDrawPhaseObserver = null;
  90585. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90586. this._onAfterDrawPhaseObserver = null;
  90587. }
  90588. },
  90589. enumerable: true,
  90590. configurable: true
  90591. });
  90592. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  90593. /**
  90594. * Gets the perf counter used for draw calls
  90595. */
  90596. get: function () {
  90597. return this.scene.getEngine()._drawCalls;
  90598. },
  90599. enumerable: true,
  90600. configurable: true
  90601. });
  90602. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  90603. /**
  90604. * Gets the perf counter used for texture collisions
  90605. */
  90606. get: function () {
  90607. return this.scene.getEngine()._textureCollisions;
  90608. },
  90609. enumerable: true,
  90610. configurable: true
  90611. });
  90612. SceneInstrumentation.prototype.dispose = function () {
  90613. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  90614. this._onAfterRenderObserver = null;
  90615. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90616. this._onBeforeActiveMeshesEvaluationObserver = null;
  90617. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90618. this._onAfterActiveMeshesEvaluationObserver = null;
  90619. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90620. this._onBeforeRenderTargetsRenderObserver = null;
  90621. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90622. this._onAfterRenderTargetsRenderObserver = null;
  90623. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  90624. this._onBeforeAnimationsObserver = null;
  90625. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90626. this._onBeforeParticlesRenderingObserver = null;
  90627. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90628. this._onAfterParticlesRenderingObserver = null;
  90629. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90630. this._onBeforeSpritesRenderingObserver = null;
  90631. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90632. this._onAfterSpritesRenderingObserver = null;
  90633. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90634. this._onBeforeDrawPhaseObserver = null;
  90635. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90636. this._onAfterDrawPhaseObserver = null;
  90637. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90638. this._onBeforePhysicsObserver = null;
  90639. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90640. this._onAfterPhysicsObserver = null;
  90641. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90642. this._onAfterAnimationsObserver = null;
  90643. this.scene = null;
  90644. };
  90645. return SceneInstrumentation;
  90646. }());
  90647. BABYLON.SceneInstrumentation = SceneInstrumentation;
  90648. })(BABYLON || (BABYLON = {}));
  90649. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  90650. "use strict";
  90651. var BABYLON;
  90652. (function (BABYLON) {
  90653. var _TimeToken = /** @class */ (function () {
  90654. function _TimeToken() {
  90655. this._timeElapsedQueryEnded = false;
  90656. }
  90657. return _TimeToken;
  90658. }());
  90659. BABYLON._TimeToken = _TimeToken;
  90660. })(BABYLON || (BABYLON = {}));
  90661. //# sourceMappingURL=babylon.timeToken.js.map
  90662. "use strict";
  90663. var BABYLON;
  90664. (function (BABYLON) {
  90665. /**
  90666. * Background material defines definition.
  90667. * @ignore Mainly internal Use
  90668. */
  90669. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  90670. __extends(BackgroundMaterialDefines, _super);
  90671. /**
  90672. * Constructor of the defines.
  90673. */
  90674. function BackgroundMaterialDefines() {
  90675. var _this = _super.call(this) || this;
  90676. /**
  90677. * True if the diffuse texture is in use.
  90678. */
  90679. _this.DIFFUSE = false;
  90680. /**
  90681. * The direct UV channel to use.
  90682. */
  90683. _this.DIFFUSEDIRECTUV = 0;
  90684. /**
  90685. * True if the diffuse texture is in gamma space.
  90686. */
  90687. _this.GAMMADIFFUSE = false;
  90688. /**
  90689. * True if the diffuse texture has opacity in the alpha channel.
  90690. */
  90691. _this.DIFFUSEHASALPHA = false;
  90692. /**
  90693. * True if you want the material to fade to transparent at grazing angle.
  90694. */
  90695. _this.OPACITYFRESNEL = false;
  90696. /**
  90697. * True if an extra blur needs to be added in the reflection.
  90698. */
  90699. _this.REFLECTIONBLUR = false;
  90700. /**
  90701. * True if you want the material to fade to reflection at grazing angle.
  90702. */
  90703. _this.REFLECTIONFRESNEL = false;
  90704. /**
  90705. * True if you want the material to falloff as far as you move away from the scene center.
  90706. */
  90707. _this.REFLECTIONFALLOFF = false;
  90708. /**
  90709. * False if the current Webgl implementation does not support the texture lod extension.
  90710. */
  90711. _this.TEXTURELODSUPPORT = false;
  90712. /**
  90713. * True to ensure the data are premultiplied.
  90714. */
  90715. _this.PREMULTIPLYALPHA = false;
  90716. /**
  90717. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  90718. */
  90719. _this.USERGBCOLOR = false;
  90720. /**
  90721. * True to add noise in order to reduce the banding effect.
  90722. */
  90723. _this.NOISE = false;
  90724. /**
  90725. * is the reflection texture in BGR color scheme?
  90726. * Mainly used to solve a bug in ios10 video tag
  90727. */
  90728. _this.REFLECTIONBGR = false;
  90729. _this.IMAGEPROCESSING = false;
  90730. _this.VIGNETTE = false;
  90731. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  90732. _this.VIGNETTEBLENDMODEOPAQUE = false;
  90733. _this.TONEMAPPING = false;
  90734. _this.CONTRAST = false;
  90735. _this.COLORCURVES = false;
  90736. _this.COLORGRADING = false;
  90737. _this.COLORGRADING3D = false;
  90738. _this.SAMPLER3DGREENDEPTH = false;
  90739. _this.SAMPLER3DBGRMAP = false;
  90740. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  90741. _this.EXPOSURE = false;
  90742. _this.GRAIN = false;
  90743. // Reflection.
  90744. _this.REFLECTION = false;
  90745. _this.REFLECTIONMAP_3D = false;
  90746. _this.REFLECTIONMAP_SPHERICAL = false;
  90747. _this.REFLECTIONMAP_PLANAR = false;
  90748. _this.REFLECTIONMAP_CUBIC = false;
  90749. _this.REFLECTIONMAP_PROJECTION = false;
  90750. _this.REFLECTIONMAP_SKYBOX = false;
  90751. _this.REFLECTIONMAP_EXPLICIT = false;
  90752. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  90753. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  90754. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  90755. _this.INVERTCUBICMAP = false;
  90756. _this.REFLECTIONMAP_OPPOSITEZ = false;
  90757. _this.LODINREFLECTIONALPHA = false;
  90758. _this.GAMMAREFLECTION = false;
  90759. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  90760. // Default BJS.
  90761. _this.MAINUV1 = false;
  90762. _this.MAINUV2 = false;
  90763. _this.UV1 = false;
  90764. _this.UV2 = false;
  90765. _this.CLIPPLANE = false;
  90766. _this.POINTSIZE = false;
  90767. _this.FOG = false;
  90768. _this.NORMAL = false;
  90769. _this.NUM_BONE_INFLUENCERS = 0;
  90770. _this.BonesPerMesh = 0;
  90771. _this.INSTANCES = false;
  90772. _this.SHADOWFLOAT = false;
  90773. _this.rebuild();
  90774. return _this;
  90775. }
  90776. return BackgroundMaterialDefines;
  90777. }(BABYLON.MaterialDefines));
  90778. /**
  90779. * Background material used to create an efficient environement around your scene.
  90780. */
  90781. var BackgroundMaterial = /** @class */ (function (_super) {
  90782. __extends(BackgroundMaterial, _super);
  90783. /**
  90784. * Instantiates a Background Material in the given scene
  90785. * @param name The friendly name of the material
  90786. * @param scene The scene to add the material to
  90787. */
  90788. function BackgroundMaterial(name, scene) {
  90789. var _this = _super.call(this, name, scene) || this;
  90790. /**
  90791. * Key light Color (multiply against the R channel of the environement texture)
  90792. */
  90793. _this.primaryColor = BABYLON.Color3.White();
  90794. /**
  90795. * Key light Level (allowing HDR output of the background)
  90796. */
  90797. _this.primaryLevel = 1;
  90798. /**
  90799. * Secondary light Color (multiply against the G channel of the environement texture)
  90800. */
  90801. _this.secondaryColor = BABYLON.Color3.Gray();
  90802. /**
  90803. * Secondary light Level (allowing HDR output of the background)
  90804. */
  90805. _this.secondaryLevel = 1;
  90806. /**
  90807. * Tertiary light Color (multiply against the B channel of the environement texture)
  90808. */
  90809. _this.tertiaryColor = BABYLON.Color3.Black();
  90810. /**
  90811. * Tertiary light Level (allowing HDR output of the background)
  90812. */
  90813. _this.tertiaryLevel = 1;
  90814. /**
  90815. * Reflection Texture used in the material.
  90816. * Should be author in a specific way for the best result (refer to the documentation).
  90817. */
  90818. _this.reflectionTexture = null;
  90819. /**
  90820. * Reflection Texture level of blur.
  90821. *
  90822. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  90823. * texture twice.
  90824. */
  90825. _this.reflectionBlur = 0;
  90826. /**
  90827. * Diffuse Texture used in the material.
  90828. * Should be author in a specific way for the best result (refer to the documentation).
  90829. */
  90830. _this.diffuseTexture = null;
  90831. _this._shadowLights = null;
  90832. /**
  90833. * Specify the list of lights casting shadow on the material.
  90834. * All scene shadow lights will be included if null.
  90835. */
  90836. _this.shadowLights = null;
  90837. /**
  90838. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  90839. * soft lighting on the background.
  90840. */
  90841. _this.shadowBlurScale = 1;
  90842. /**
  90843. * Helps adjusting the shadow to a softer level if required.
  90844. * 0 means black shadows and 1 means no shadows.
  90845. */
  90846. _this.shadowLevel = 0;
  90847. /**
  90848. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  90849. * It is usually zero but might be interesting to modify according to your setup.
  90850. */
  90851. _this.sceneCenter = BABYLON.Vector3.Zero();
  90852. /**
  90853. * This helps specifying that the material is falling off to the sky box at grazing angle.
  90854. * This helps ensuring a nice transition when the camera goes under the ground.
  90855. */
  90856. _this.opacityFresnel = true;
  90857. /**
  90858. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  90859. * This helps adding a mirror texture on the ground.
  90860. */
  90861. _this.reflectionFresnel = false;
  90862. /**
  90863. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  90864. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  90865. */
  90866. _this.reflectionFalloffDistance = 0.0;
  90867. /**
  90868. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  90869. */
  90870. _this.reflectionAmount = 1.0;
  90871. /**
  90872. * This specifies the weight of the reflection at grazing angle.
  90873. */
  90874. _this.reflectionReflectance0 = 0.05;
  90875. /**
  90876. * This specifies the weight of the reflection at a perpendicular point of view.
  90877. */
  90878. _this.reflectionReflectance90 = 0.5;
  90879. /**
  90880. * Helps to directly use the maps channels instead of their level.
  90881. */
  90882. _this.useRGBColor = true;
  90883. /**
  90884. * This helps reducing the banding effect that could occur on the background.
  90885. */
  90886. _this.enableNoise = false;
  90887. _this._fovMultiplier = 1.0;
  90888. /**
  90889. * Enable the FOV adjustment feature controlled by fovMultiplier.
  90890. * @type {boolean}
  90891. */
  90892. _this.useEquirectangularFOV = false;
  90893. _this._maxSimultaneousLights = 4;
  90894. /**
  90895. * Number of Simultaneous lights allowed on the material.
  90896. */
  90897. _this.maxSimultaneousLights = 4;
  90898. /**
  90899. * Keep track of the image processing observer to allow dispose and replace.
  90900. */
  90901. _this._imageProcessingObserver = null;
  90902. /**
  90903. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  90904. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  90905. */
  90906. _this.switchToBGR = false;
  90907. // Temp values kept as cache in the material.
  90908. _this._renderTargets = new BABYLON.SmartArray(16);
  90909. _this._reflectionControls = BABYLON.Vector4.Zero();
  90910. // Setup the default processing configuration to the scene.
  90911. _this._attachImageProcessingConfiguration(null);
  90912. _this.getRenderTargetTextures = function () {
  90913. _this._renderTargets.reset();
  90914. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  90915. _this._renderTargets.push(_this._diffuseTexture);
  90916. }
  90917. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  90918. _this._renderTargets.push(_this._reflectionTexture);
  90919. }
  90920. return _this._renderTargets;
  90921. };
  90922. return _this;
  90923. }
  90924. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  90925. /**
  90926. * Sets the reflection reflectance fresnel values according to the default standard
  90927. * empirically know to work well :-)
  90928. */
  90929. set: function (value) {
  90930. var reflectionWeight = value;
  90931. if (reflectionWeight < 0.5) {
  90932. reflectionWeight = reflectionWeight * 2.0;
  90933. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  90934. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  90935. }
  90936. else {
  90937. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  90938. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  90939. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  90940. }
  90941. },
  90942. enumerable: true,
  90943. configurable: true
  90944. });
  90945. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  90946. /**
  90947. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  90948. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  90949. * Recommended to be keep at 1.0 except for special cases.
  90950. */
  90951. get: function () {
  90952. return this._fovMultiplier;
  90953. },
  90954. set: function (value) {
  90955. if (isNaN(value)) {
  90956. value = 1.0;
  90957. }
  90958. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  90959. },
  90960. enumerable: true,
  90961. configurable: true
  90962. });
  90963. /**
  90964. * Attaches a new image processing configuration to the PBR Material.
  90965. * @param configuration (if null the scene configuration will be use)
  90966. */
  90967. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  90968. var _this = this;
  90969. if (configuration === this._imageProcessingConfiguration) {
  90970. return;
  90971. }
  90972. // Detaches observer.
  90973. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90974. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90975. }
  90976. // Pick the scene configuration if needed.
  90977. if (!configuration) {
  90978. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  90979. }
  90980. else {
  90981. this._imageProcessingConfiguration = configuration;
  90982. }
  90983. // Attaches observer.
  90984. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  90985. _this._markAllSubMeshesAsImageProcessingDirty();
  90986. });
  90987. };
  90988. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  90989. /**
  90990. * Gets the image processing configuration used either in this material.
  90991. */
  90992. get: function () {
  90993. return this._imageProcessingConfiguration;
  90994. },
  90995. /**
  90996. * Sets the Default image processing configuration used either in the this material.
  90997. *
  90998. * If sets to null, the scene one is in use.
  90999. */
  91000. set: function (value) {
  91001. this._attachImageProcessingConfiguration(value);
  91002. // Ensure the effect will be rebuilt.
  91003. this._markAllSubMeshesAsTexturesDirty();
  91004. },
  91005. enumerable: true,
  91006. configurable: true
  91007. });
  91008. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  91009. /**
  91010. * Gets wether the color curves effect is enabled.
  91011. */
  91012. get: function () {
  91013. return this.imageProcessingConfiguration.colorCurvesEnabled;
  91014. },
  91015. /**
  91016. * Sets wether the color curves effect is enabled.
  91017. */
  91018. set: function (value) {
  91019. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  91020. },
  91021. enumerable: true,
  91022. configurable: true
  91023. });
  91024. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  91025. /**
  91026. * Gets wether the color grading effect is enabled.
  91027. */
  91028. get: function () {
  91029. return this.imageProcessingConfiguration.colorGradingEnabled;
  91030. },
  91031. /**
  91032. * Gets wether the color grading effect is enabled.
  91033. */
  91034. set: function (value) {
  91035. this.imageProcessingConfiguration.colorGradingEnabled = value;
  91036. },
  91037. enumerable: true,
  91038. configurable: true
  91039. });
  91040. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  91041. /**
  91042. * Gets wether tonemapping is enabled or not.
  91043. */
  91044. get: function () {
  91045. return this._imageProcessingConfiguration.toneMappingEnabled;
  91046. },
  91047. /**
  91048. * Sets wether tonemapping is enabled or not
  91049. */
  91050. set: function (value) {
  91051. this._imageProcessingConfiguration.toneMappingEnabled = value;
  91052. },
  91053. enumerable: true,
  91054. configurable: true
  91055. });
  91056. ;
  91057. ;
  91058. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  91059. /**
  91060. * The camera exposure used on this material.
  91061. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91062. * This corresponds to a photographic exposure.
  91063. */
  91064. get: function () {
  91065. return this._imageProcessingConfiguration.exposure;
  91066. },
  91067. /**
  91068. * The camera exposure used on this material.
  91069. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91070. * This corresponds to a photographic exposure.
  91071. */
  91072. set: function (value) {
  91073. this._imageProcessingConfiguration.exposure = value;
  91074. },
  91075. enumerable: true,
  91076. configurable: true
  91077. });
  91078. ;
  91079. ;
  91080. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  91081. /**
  91082. * Gets The camera contrast used on this material.
  91083. */
  91084. get: function () {
  91085. return this._imageProcessingConfiguration.contrast;
  91086. },
  91087. /**
  91088. * Sets The camera contrast used on this material.
  91089. */
  91090. set: function (value) {
  91091. this._imageProcessingConfiguration.contrast = value;
  91092. },
  91093. enumerable: true,
  91094. configurable: true
  91095. });
  91096. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  91097. /**
  91098. * Gets the Color Grading 2D Lookup Texture.
  91099. */
  91100. get: function () {
  91101. return this._imageProcessingConfiguration.colorGradingTexture;
  91102. },
  91103. /**
  91104. * Sets the Color Grading 2D Lookup Texture.
  91105. */
  91106. set: function (value) {
  91107. this.imageProcessingConfiguration.colorGradingTexture = value;
  91108. },
  91109. enumerable: true,
  91110. configurable: true
  91111. });
  91112. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  91113. /**
  91114. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91115. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91116. * 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;
  91117. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91118. */
  91119. get: function () {
  91120. return this.imageProcessingConfiguration.colorCurves;
  91121. },
  91122. /**
  91123. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91124. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91125. * 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;
  91126. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91127. */
  91128. set: function (value) {
  91129. this.imageProcessingConfiguration.colorCurves = value;
  91130. },
  91131. enumerable: true,
  91132. configurable: true
  91133. });
  91134. /**
  91135. * The entire material has been created in order to prevent overdraw.
  91136. * @returns false
  91137. */
  91138. BackgroundMaterial.prototype.needAlphaTesting = function () {
  91139. return true;
  91140. };
  91141. /**
  91142. * The entire material has been created in order to prevent overdraw.
  91143. * @returns true if blending is enable
  91144. */
  91145. BackgroundMaterial.prototype.needAlphaBlending = function () {
  91146. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  91147. };
  91148. /**
  91149. * Checks wether the material is ready to be rendered for a given mesh.
  91150. * @param mesh The mesh to render
  91151. * @param subMesh The submesh to check against
  91152. * @param useInstances Specify wether or not the material is used with instances
  91153. * @returns true if all the dependencies are ready (Textures, Effects...)
  91154. */
  91155. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  91156. var _this = this;
  91157. if (useInstances === void 0) { useInstances = false; }
  91158. if (subMesh.effect && this.isFrozen) {
  91159. if (this._wasPreviouslyReady) {
  91160. return true;
  91161. }
  91162. }
  91163. if (!subMesh._materialDefines) {
  91164. subMesh._materialDefines = new BackgroundMaterialDefines();
  91165. }
  91166. var scene = this.getScene();
  91167. var defines = subMesh._materialDefines;
  91168. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  91169. if (defines._renderId === scene.getRenderId()) {
  91170. return true;
  91171. }
  91172. }
  91173. var engine = scene.getEngine();
  91174. // Lights
  91175. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  91176. defines._needNormals = true;
  91177. // Textures
  91178. if (defines._areTexturesDirty) {
  91179. defines._needUVs = false;
  91180. if (scene.texturesEnabled) {
  91181. if (scene.getEngine().getCaps().textureLOD) {
  91182. defines.TEXTURELODSUPPORT = true;
  91183. }
  91184. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91185. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  91186. return false;
  91187. }
  91188. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  91189. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  91190. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  91191. defines.OPACITYFRESNEL = this._opacityFresnel;
  91192. }
  91193. else {
  91194. defines.DIFFUSE = false;
  91195. defines.DIFFUSEHASALPHA = false;
  91196. defines.GAMMADIFFUSE = false;
  91197. defines.OPACITYFRESNEL = false;
  91198. }
  91199. var reflectionTexture = this._reflectionTexture;
  91200. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91201. if (!reflectionTexture.isReadyOrNotBlocking()) {
  91202. return false;
  91203. }
  91204. defines.REFLECTION = true;
  91205. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  91206. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  91207. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  91208. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  91209. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  91210. defines.REFLECTIONBGR = this.switchToBGR;
  91211. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  91212. defines.INVERTCUBICMAP = true;
  91213. }
  91214. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  91215. switch (reflectionTexture.coordinatesMode) {
  91216. case BABYLON.Texture.CUBIC_MODE:
  91217. case BABYLON.Texture.INVCUBIC_MODE:
  91218. defines.REFLECTIONMAP_CUBIC = true;
  91219. break;
  91220. case BABYLON.Texture.EXPLICIT_MODE:
  91221. defines.REFLECTIONMAP_EXPLICIT = true;
  91222. break;
  91223. case BABYLON.Texture.PLANAR_MODE:
  91224. defines.REFLECTIONMAP_PLANAR = true;
  91225. break;
  91226. case BABYLON.Texture.PROJECTION_MODE:
  91227. defines.REFLECTIONMAP_PROJECTION = true;
  91228. break;
  91229. case BABYLON.Texture.SKYBOX_MODE:
  91230. defines.REFLECTIONMAP_SKYBOX = true;
  91231. break;
  91232. case BABYLON.Texture.SPHERICAL_MODE:
  91233. defines.REFLECTIONMAP_SPHERICAL = true;
  91234. break;
  91235. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  91236. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  91237. break;
  91238. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  91239. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  91240. break;
  91241. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  91242. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  91243. break;
  91244. }
  91245. if (this.reflectionFresnel) {
  91246. defines.REFLECTIONFRESNEL = true;
  91247. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  91248. this._reflectionControls.x = this.reflectionAmount;
  91249. this._reflectionControls.y = this.reflectionReflectance0;
  91250. this._reflectionControls.z = this.reflectionReflectance90;
  91251. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  91252. }
  91253. else {
  91254. defines.REFLECTIONFRESNEL = false;
  91255. defines.REFLECTIONFALLOFF = false;
  91256. }
  91257. }
  91258. else {
  91259. defines.REFLECTION = false;
  91260. defines.REFLECTIONFALLOFF = false;
  91261. defines.REFLECTIONBLUR = false;
  91262. defines.REFLECTIONMAP_3D = false;
  91263. defines.REFLECTIONMAP_SPHERICAL = false;
  91264. defines.REFLECTIONMAP_PLANAR = false;
  91265. defines.REFLECTIONMAP_CUBIC = false;
  91266. defines.REFLECTIONMAP_PROJECTION = false;
  91267. defines.REFLECTIONMAP_SKYBOX = false;
  91268. defines.REFLECTIONMAP_EXPLICIT = false;
  91269. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  91270. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  91271. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  91272. defines.INVERTCUBICMAP = false;
  91273. defines.REFLECTIONMAP_OPPOSITEZ = false;
  91274. defines.LODINREFLECTIONALPHA = false;
  91275. defines.GAMMAREFLECTION = false;
  91276. }
  91277. }
  91278. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  91279. defines.USERGBCOLOR = this._useRGBColor;
  91280. defines.NOISE = this._enableNoise;
  91281. }
  91282. if (defines._areImageProcessingDirty) {
  91283. if (!this._imageProcessingConfiguration.isReady()) {
  91284. return false;
  91285. }
  91286. this._imageProcessingConfiguration.prepareDefines(defines);
  91287. }
  91288. // Misc.
  91289. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  91290. // Values that need to be evaluated on every frame
  91291. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  91292. // Attribs
  91293. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  91294. if (mesh) {
  91295. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  91296. mesh.createNormals(true);
  91297. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  91298. }
  91299. }
  91300. }
  91301. // Get correct effect
  91302. if (defines.isDirty) {
  91303. defines.markAsProcessed();
  91304. scene.resetCachedMaterial();
  91305. // Fallbacks
  91306. var fallbacks = new BABYLON.EffectFallbacks();
  91307. if (defines.FOG) {
  91308. fallbacks.addFallback(0, "FOG");
  91309. }
  91310. if (defines.POINTSIZE) {
  91311. fallbacks.addFallback(1, "POINTSIZE");
  91312. }
  91313. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  91314. if (defines.NUM_BONE_INFLUENCERS > 0) {
  91315. fallbacks.addCPUSkinningFallback(0, mesh);
  91316. }
  91317. //Attributes
  91318. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91319. if (defines.NORMAL) {
  91320. attribs.push(BABYLON.VertexBuffer.NormalKind);
  91321. }
  91322. if (defines.UV1) {
  91323. attribs.push(BABYLON.VertexBuffer.UVKind);
  91324. }
  91325. if (defines.UV2) {
  91326. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91327. }
  91328. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  91329. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  91330. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  91331. "vFogInfos", "vFogColor", "pointSize",
  91332. "vClipPlane", "mBones",
  91333. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  91334. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  91335. "shadowLevel", "alpha",
  91336. "vBackgroundCenter", "vReflectionControl",
  91337. "vDiffuseInfos", "diffuseMatrix",
  91338. ];
  91339. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  91340. var uniformBuffers = ["Material", "Scene"];
  91341. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  91342. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  91343. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  91344. uniformsNames: uniforms,
  91345. uniformBuffersNames: uniformBuffers,
  91346. samplers: samplers,
  91347. defines: defines,
  91348. maxSimultaneousLights: this._maxSimultaneousLights
  91349. });
  91350. var onCompiled = function (effect) {
  91351. if (_this.onCompiled) {
  91352. _this.onCompiled(effect);
  91353. }
  91354. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  91355. };
  91356. var join = defines.toString();
  91357. subMesh.setEffect(scene.getEngine().createEffect("background", {
  91358. attributes: attribs,
  91359. uniformsNames: uniforms,
  91360. uniformBuffersNames: uniformBuffers,
  91361. samplers: samplers,
  91362. defines: join,
  91363. fallbacks: fallbacks,
  91364. onCompiled: onCompiled,
  91365. onError: this.onError,
  91366. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  91367. }, engine), defines);
  91368. this.buildUniformLayout();
  91369. }
  91370. if (!subMesh.effect || !subMesh.effect.isReady()) {
  91371. return false;
  91372. }
  91373. defines._renderId = scene.getRenderId();
  91374. this._wasPreviouslyReady = true;
  91375. return true;
  91376. };
  91377. /**
  91378. * Build the uniform buffer used in the material.
  91379. */
  91380. BackgroundMaterial.prototype.buildUniformLayout = function () {
  91381. // Order is important !
  91382. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  91383. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  91384. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  91385. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  91386. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  91387. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  91388. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  91389. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  91390. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  91391. this._uniformBuffer.addUniform("pointSize", 1);
  91392. this._uniformBuffer.addUniform("shadowLevel", 1);
  91393. this._uniformBuffer.addUniform("alpha", 1);
  91394. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  91395. this._uniformBuffer.addUniform("vReflectionControl", 4);
  91396. this._uniformBuffer.create();
  91397. };
  91398. /**
  91399. * Unbind the material.
  91400. */
  91401. BackgroundMaterial.prototype.unbind = function () {
  91402. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  91403. this._uniformBuffer.setTexture("diffuseSampler", null);
  91404. }
  91405. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  91406. this._uniformBuffer.setTexture("reflectionSampler", null);
  91407. }
  91408. _super.prototype.unbind.call(this);
  91409. };
  91410. /**
  91411. * Bind only the world matrix to the material.
  91412. * @param world The world matrix to bind.
  91413. */
  91414. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  91415. this._activeEffect.setMatrix("world", world);
  91416. };
  91417. /**
  91418. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  91419. * @param world The world matrix to bind.
  91420. * @param subMesh The submesh to bind for.
  91421. */
  91422. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  91423. var scene = this.getScene();
  91424. var defines = subMesh._materialDefines;
  91425. if (!defines) {
  91426. return;
  91427. }
  91428. var effect = subMesh.effect;
  91429. if (!effect) {
  91430. return;
  91431. }
  91432. this._activeEffect = effect;
  91433. // Matrices
  91434. this.bindOnlyWorldMatrix(world);
  91435. // Bones
  91436. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  91437. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  91438. if (mustRebind) {
  91439. this._uniformBuffer.bindToEffect(effect, "Material");
  91440. this.bindViewProjection(effect);
  91441. var reflectionTexture = this._reflectionTexture;
  91442. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  91443. // Texture uniforms
  91444. if (scene.texturesEnabled) {
  91445. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91446. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  91447. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  91448. }
  91449. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91450. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  91451. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  91452. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  91453. }
  91454. }
  91455. if (this.shadowLevel > 0) {
  91456. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  91457. }
  91458. this._uniformBuffer.updateFloat("alpha", this.alpha);
  91459. // Point size
  91460. if (this.pointsCloud) {
  91461. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  91462. }
  91463. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  91464. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  91465. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  91466. }
  91467. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  91468. // Textures
  91469. if (scene.texturesEnabled) {
  91470. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91471. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  91472. }
  91473. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91474. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  91475. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91476. }
  91477. else if (!defines.REFLECTIONBLUR) {
  91478. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91479. }
  91480. else {
  91481. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  91482. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  91483. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  91484. }
  91485. if (defines.REFLECTIONFRESNEL) {
  91486. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  91487. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  91488. }
  91489. }
  91490. }
  91491. // Clip plane
  91492. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  91493. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  91494. }
  91495. if (mustRebind || !this.isFrozen) {
  91496. if (scene.lightsEnabled) {
  91497. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  91498. }
  91499. // View
  91500. this.bindView(effect);
  91501. // Fog
  91502. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  91503. // image processing
  91504. this._imageProcessingConfiguration.bind(this._activeEffect);
  91505. }
  91506. this._uniformBuffer.update();
  91507. this._afterBind(mesh);
  91508. };
  91509. /**
  91510. * Dispose the material.
  91511. * @param forceDisposeEffect Force disposal of the associated effect.
  91512. * @param forceDisposeTextures Force disposal of the associated textures.
  91513. */
  91514. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  91515. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  91516. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  91517. if (forceDisposeTextures) {
  91518. if (this.diffuseTexture) {
  91519. this.diffuseTexture.dispose();
  91520. }
  91521. if (this.reflectionTexture) {
  91522. this.reflectionTexture.dispose();
  91523. }
  91524. }
  91525. this._renderTargets.dispose();
  91526. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91527. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91528. }
  91529. _super.prototype.dispose.call(this, forceDisposeEffect);
  91530. };
  91531. /**
  91532. * Clones the material.
  91533. * @param name The cloned name.
  91534. * @returns The cloned material.
  91535. */
  91536. BackgroundMaterial.prototype.clone = function (name) {
  91537. var _this = this;
  91538. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  91539. };
  91540. /**
  91541. * Serializes the current material to its JSON representation.
  91542. * @returns The JSON representation.
  91543. */
  91544. BackgroundMaterial.prototype.serialize = function () {
  91545. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91546. serializationObject.customType = "BABYLON.BackgroundMaterial";
  91547. return serializationObject;
  91548. };
  91549. /**
  91550. * Gets the class name of the material
  91551. * @returns "BackgroundMaterial"
  91552. */
  91553. BackgroundMaterial.prototype.getClassName = function () {
  91554. return "BackgroundMaterial";
  91555. };
  91556. /**
  91557. * Parse a JSON input to create back a background material.
  91558. * @param source The JSON data to parse
  91559. * @param scene The scene to create the parsed material in
  91560. * @param rootUrl The root url of the assets the material depends upon
  91561. * @returns the instantiated BackgroundMaterial.
  91562. */
  91563. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  91564. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  91565. };
  91566. /**
  91567. * Standard reflectance value at parallel view angle.
  91568. */
  91569. BackgroundMaterial.StandardReflectance0 = 0.05;
  91570. /**
  91571. * Standard reflectance value at grazing angle.
  91572. */
  91573. BackgroundMaterial.StandardReflectance90 = 0.5;
  91574. __decorate([
  91575. BABYLON.serializeAsColor3()
  91576. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  91577. __decorate([
  91578. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91579. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  91580. __decorate([
  91581. BABYLON.serialize()
  91582. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  91583. __decorate([
  91584. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91585. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  91586. __decorate([
  91587. BABYLON.serializeAsColor3()
  91588. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  91589. __decorate([
  91590. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91591. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  91592. __decorate([
  91593. BABYLON.serialize()
  91594. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  91595. __decorate([
  91596. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91597. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  91598. __decorate([
  91599. BABYLON.serializeAsColor3()
  91600. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  91601. __decorate([
  91602. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91603. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  91604. __decorate([
  91605. BABYLON.serialize()
  91606. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  91607. __decorate([
  91608. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91609. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  91610. __decorate([
  91611. BABYLON.serializeAsTexture()
  91612. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  91613. __decorate([
  91614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91615. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  91616. __decorate([
  91617. BABYLON.serialize()
  91618. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  91619. __decorate([
  91620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91621. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  91622. __decorate([
  91623. BABYLON.serializeAsTexture()
  91624. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  91625. __decorate([
  91626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91627. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  91628. __decorate([
  91629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91630. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  91631. __decorate([
  91632. BABYLON.serialize()
  91633. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  91634. __decorate([
  91635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91636. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  91637. __decorate([
  91638. BABYLON.serialize()
  91639. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  91640. __decorate([
  91641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91642. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  91643. __decorate([
  91644. BABYLON.serializeAsVector3()
  91645. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  91646. __decorate([
  91647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91648. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  91649. __decorate([
  91650. BABYLON.serialize()
  91651. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  91652. __decorate([
  91653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91654. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  91655. __decorate([
  91656. BABYLON.serialize()
  91657. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  91658. __decorate([
  91659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91660. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  91661. __decorate([
  91662. BABYLON.serialize()
  91663. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  91664. __decorate([
  91665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91666. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  91667. __decorate([
  91668. BABYLON.serialize()
  91669. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  91670. __decorate([
  91671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91672. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  91673. __decorate([
  91674. BABYLON.serialize()
  91675. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  91676. __decorate([
  91677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91678. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  91679. __decorate([
  91680. BABYLON.serialize()
  91681. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  91682. __decorate([
  91683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91684. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  91685. __decorate([
  91686. BABYLON.serialize()
  91687. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  91688. __decorate([
  91689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91690. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  91691. __decorate([
  91692. BABYLON.serialize()
  91693. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  91694. __decorate([
  91695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91696. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  91697. __decorate([
  91698. BABYLON.serialize()
  91699. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  91700. __decorate([
  91701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91702. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  91703. __decorate([
  91704. BABYLON.serializeAsImageProcessingConfiguration()
  91705. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  91706. return BackgroundMaterial;
  91707. }(BABYLON.PushMaterial));
  91708. BABYLON.BackgroundMaterial = BackgroundMaterial;
  91709. })(BABYLON || (BABYLON = {}));
  91710. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  91711. "use strict";
  91712. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91713. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91714. s = arguments[i];
  91715. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91716. t[p] = s[p];
  91717. }
  91718. return t;
  91719. };
  91720. var BABYLON;
  91721. (function (BABYLON) {
  91722. /**
  91723. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  91724. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  91725. * It also helps with the default setup of your imageProcessing configuration.
  91726. */
  91727. var EnvironmentHelper = /** @class */ (function () {
  91728. /**
  91729. * constructor
  91730. * @param options
  91731. * @param scene The scene to add the material to
  91732. */
  91733. function EnvironmentHelper(options, scene) {
  91734. var _this = this;
  91735. this._errorHandler = function (message, exception) {
  91736. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  91737. };
  91738. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  91739. this._scene = scene;
  91740. this.onErrorObservable = new BABYLON.Observable();
  91741. this._setupBackground();
  91742. this._setupImageProcessing();
  91743. }
  91744. /**
  91745. * Creates the default options for the helper.
  91746. */
  91747. EnvironmentHelper._getDefaultOptions = function () {
  91748. return {
  91749. createGround: true,
  91750. groundSize: 15,
  91751. groundTexture: this._groundTextureCDNUrl,
  91752. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  91753. groundOpacity: 0.9,
  91754. enableGroundShadow: true,
  91755. groundShadowLevel: 0.5,
  91756. enableGroundMirror: false,
  91757. groundMirrorSizeRatio: 0.3,
  91758. groundMirrorBlurKernel: 64,
  91759. groundMirrorAmount: 1,
  91760. groundMirrorFresnelWeight: 1,
  91761. groundMirrorFallOffDistance: 0,
  91762. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  91763. groundYBias: 0.00001,
  91764. createSkybox: true,
  91765. skyboxSize: 20,
  91766. skyboxTexture: this._skyboxTextureCDNUrl,
  91767. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  91768. backgroundYRotation: 0,
  91769. sizeAuto: true,
  91770. rootPosition: BABYLON.Vector3.Zero(),
  91771. setupImageProcessing: true,
  91772. environmentTexture: this._environmentTextureCDNUrl,
  91773. cameraExposure: 0.8,
  91774. cameraContrast: 1.2,
  91775. toneMappingEnabled: true,
  91776. };
  91777. };
  91778. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  91779. /**
  91780. * Gets the root mesh created by the helper.
  91781. */
  91782. get: function () {
  91783. return this._rootMesh;
  91784. },
  91785. enumerable: true,
  91786. configurable: true
  91787. });
  91788. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  91789. /**
  91790. * Gets the skybox created by the helper.
  91791. */
  91792. get: function () {
  91793. return this._skybox;
  91794. },
  91795. enumerable: true,
  91796. configurable: true
  91797. });
  91798. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  91799. /**
  91800. * Gets the skybox texture created by the helper.
  91801. */
  91802. get: function () {
  91803. return this._skyboxTexture;
  91804. },
  91805. enumerable: true,
  91806. configurable: true
  91807. });
  91808. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  91809. /**
  91810. * Gets the skybox material created by the helper.
  91811. */
  91812. get: function () {
  91813. return this._skyboxMaterial;
  91814. },
  91815. enumerable: true,
  91816. configurable: true
  91817. });
  91818. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  91819. /**
  91820. * Gets the ground mesh created by the helper.
  91821. */
  91822. get: function () {
  91823. return this._ground;
  91824. },
  91825. enumerable: true,
  91826. configurable: true
  91827. });
  91828. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  91829. /**
  91830. * Gets the ground texture created by the helper.
  91831. */
  91832. get: function () {
  91833. return this._groundTexture;
  91834. },
  91835. enumerable: true,
  91836. configurable: true
  91837. });
  91838. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  91839. /**
  91840. * Gets the ground mirror created by the helper.
  91841. */
  91842. get: function () {
  91843. return this._groundMirror;
  91844. },
  91845. enumerable: true,
  91846. configurable: true
  91847. });
  91848. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  91849. /**
  91850. * Gets the ground mirror render list to helps pushing the meshes
  91851. * you wish in the ground reflection.
  91852. */
  91853. get: function () {
  91854. if (this._groundMirror) {
  91855. return this._groundMirror.renderList;
  91856. }
  91857. return null;
  91858. },
  91859. enumerable: true,
  91860. configurable: true
  91861. });
  91862. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  91863. /**
  91864. * Gets the ground material created by the helper.
  91865. */
  91866. get: function () {
  91867. return this._groundMaterial;
  91868. },
  91869. enumerable: true,
  91870. configurable: true
  91871. });
  91872. /**
  91873. * Updates the background according to the new options
  91874. * @param options
  91875. */
  91876. EnvironmentHelper.prototype.updateOptions = function (options) {
  91877. var newOptions = __assign({}, this._options, options);
  91878. if (this._ground && !newOptions.createGround) {
  91879. this._ground.dispose();
  91880. this._ground = null;
  91881. }
  91882. if (this._groundMaterial && !newOptions.createGround) {
  91883. this._groundMaterial.dispose();
  91884. this._groundMaterial = null;
  91885. }
  91886. if (this._groundTexture) {
  91887. if (this._options.groundTexture != newOptions.groundTexture) {
  91888. this._groundTexture.dispose();
  91889. this._groundTexture = null;
  91890. }
  91891. }
  91892. if (this._skybox && !newOptions.createSkybox) {
  91893. this._skybox.dispose();
  91894. this._skybox = null;
  91895. }
  91896. if (this._skyboxMaterial && !newOptions.createSkybox) {
  91897. this._skyboxMaterial.dispose();
  91898. this._skyboxMaterial = null;
  91899. }
  91900. if (this._skyboxTexture) {
  91901. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  91902. this._skyboxTexture.dispose();
  91903. this._skyboxTexture = null;
  91904. }
  91905. }
  91906. if (this._groundMirror && !newOptions.enableGroundMirror) {
  91907. this._groundMirror.dispose();
  91908. this._groundMirror = null;
  91909. }
  91910. if (this._scene.environmentTexture) {
  91911. if (this._options.environmentTexture != newOptions.environmentTexture) {
  91912. this._scene.environmentTexture.dispose();
  91913. }
  91914. }
  91915. this._options = newOptions;
  91916. this._setupBackground();
  91917. this._setupImageProcessing();
  91918. };
  91919. /**
  91920. * Sets the primary color of all the available elements.
  91921. * @param color
  91922. */
  91923. EnvironmentHelper.prototype.setMainColor = function (color) {
  91924. if (this.groundMaterial) {
  91925. this.groundMaterial.primaryColor = color;
  91926. }
  91927. if (this.skyboxMaterial) {
  91928. this.skyboxMaterial.primaryColor = color;
  91929. }
  91930. if (this.groundMirror) {
  91931. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  91932. }
  91933. };
  91934. /**
  91935. * Setup the image processing according to the specified options.
  91936. */
  91937. EnvironmentHelper.prototype._setupImageProcessing = function () {
  91938. if (this._options.setupImageProcessing) {
  91939. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  91940. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  91941. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  91942. this._setupEnvironmentTexture();
  91943. }
  91944. };
  91945. /**
  91946. * Setup the environment texture according to the specified options.
  91947. */
  91948. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  91949. if (this._scene.environmentTexture) {
  91950. return;
  91951. }
  91952. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  91953. this._scene.environmentTexture = this._options.environmentTexture;
  91954. return;
  91955. }
  91956. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  91957. this._scene.environmentTexture = environmentTexture;
  91958. };
  91959. /**
  91960. * Setup the background according to the specified options.
  91961. */
  91962. EnvironmentHelper.prototype._setupBackground = function () {
  91963. if (!this._rootMesh) {
  91964. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  91965. }
  91966. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  91967. var sceneSize = this._getSceneSize();
  91968. if (this._options.createGround) {
  91969. this._setupGround(sceneSize);
  91970. this._setupGroundMaterial();
  91971. this._setupGroundDiffuseTexture();
  91972. if (this._options.enableGroundMirror) {
  91973. this._setupGroundMirrorTexture(sceneSize);
  91974. }
  91975. this._setupMirrorInGroundMaterial();
  91976. }
  91977. if (this._options.createSkybox) {
  91978. this._setupSkybox(sceneSize);
  91979. this._setupSkyboxMaterial();
  91980. this._setupSkyboxReflectionTexture();
  91981. }
  91982. this._rootMesh.position.x = sceneSize.rootPosition.x;
  91983. this._rootMesh.position.z = sceneSize.rootPosition.z;
  91984. this._rootMesh.position.y = sceneSize.rootPosition.y;
  91985. };
  91986. /**
  91987. * Get the scene sizes according to the setup.
  91988. */
  91989. EnvironmentHelper.prototype._getSceneSize = function () {
  91990. var _this = this;
  91991. var groundSize = this._options.groundSize;
  91992. var skyboxSize = this._options.skyboxSize;
  91993. var rootPosition = this._options.rootPosition;
  91994. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  91995. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  91996. }
  91997. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  91998. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  91999. });
  92000. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  92001. if (this._options.sizeAuto) {
  92002. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  92003. this._scene.activeCamera.upperRadiusLimit) {
  92004. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  92005. skyboxSize = groundSize;
  92006. }
  92007. var sceneDiagonalLenght = sceneDiagonal.length();
  92008. if (sceneDiagonalLenght > groundSize) {
  92009. groundSize = sceneDiagonalLenght * 2;
  92010. skyboxSize = groundSize;
  92011. }
  92012. // 10 % bigger.
  92013. groundSize *= 1.1;
  92014. skyboxSize *= 1.5;
  92015. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  92016. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  92017. }
  92018. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92019. };
  92020. /**
  92021. * Setup the ground according to the specified options.
  92022. */
  92023. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  92024. var _this = this;
  92025. if (!this._ground) {
  92026. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  92027. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  92028. this._ground.parent = this._rootMesh;
  92029. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  92030. }
  92031. this._ground.receiveShadows = this._options.enableGroundShadow;
  92032. };
  92033. /**
  92034. * Setup the ground material according to the specified options.
  92035. */
  92036. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  92037. if (!this._groundMaterial) {
  92038. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  92039. }
  92040. this._groundMaterial.alpha = this._options.groundOpacity;
  92041. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  92042. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  92043. this._groundMaterial.primaryLevel = 1;
  92044. this._groundMaterial.primaryColor = this._options.groundColor;
  92045. this._groundMaterial.secondaryLevel = 0;
  92046. this._groundMaterial.tertiaryLevel = 0;
  92047. this._groundMaterial.useRGBColor = false;
  92048. this._groundMaterial.enableNoise = true;
  92049. if (this._ground) {
  92050. this._ground.material = this._groundMaterial;
  92051. }
  92052. };
  92053. /**
  92054. * Setup the ground diffuse texture according to the specified options.
  92055. */
  92056. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  92057. if (!this._groundMaterial) {
  92058. return;
  92059. }
  92060. if (this._groundTexture) {
  92061. return;
  92062. }
  92063. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  92064. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  92065. return;
  92066. }
  92067. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92068. diffuseTexture.gammaSpace = false;
  92069. diffuseTexture.hasAlpha = true;
  92070. this._groundMaterial.diffuseTexture = diffuseTexture;
  92071. };
  92072. /**
  92073. * Setup the ground mirror texture according to the specified options.
  92074. */
  92075. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  92076. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92077. if (!this._groundMirror) {
  92078. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  92079. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  92080. this._groundMirror.anisotropicFilteringLevel = 1;
  92081. this._groundMirror.wrapU = wrapping;
  92082. this._groundMirror.wrapV = wrapping;
  92083. this._groundMirror.gammaSpace = false;
  92084. if (this._groundMirror.renderList) {
  92085. for (var i = 0; i < this._scene.meshes.length; i++) {
  92086. var mesh = this._scene.meshes[i];
  92087. if (mesh !== this._ground &&
  92088. mesh !== this._skybox &&
  92089. mesh !== this._rootMesh) {
  92090. this._groundMirror.renderList.push(mesh);
  92091. }
  92092. }
  92093. }
  92094. }
  92095. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  92096. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  92097. };
  92098. /**
  92099. * Setup the ground to receive the mirror texture.
  92100. */
  92101. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  92102. if (this._groundMaterial) {
  92103. this._groundMaterial.reflectionTexture = this._groundMirror;
  92104. this._groundMaterial.reflectionFresnel = true;
  92105. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  92106. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  92107. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  92108. }
  92109. };
  92110. /**
  92111. * Setup the skybox according to the specified options.
  92112. */
  92113. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  92114. var _this = this;
  92115. if (!this._skybox) {
  92116. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  92117. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  92118. }
  92119. this._skybox.parent = this._rootMesh;
  92120. };
  92121. /**
  92122. * Setup the skybox material according to the specified options.
  92123. */
  92124. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  92125. if (!this._skybox) {
  92126. return;
  92127. }
  92128. if (!this._skyboxMaterial) {
  92129. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  92130. }
  92131. this._skyboxMaterial.useRGBColor = false;
  92132. this._skyboxMaterial.primaryLevel = 1;
  92133. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  92134. this._skyboxMaterial.secondaryLevel = 0;
  92135. this._skyboxMaterial.tertiaryLevel = 0;
  92136. this._skyboxMaterial.enableNoise = true;
  92137. this._skybox.material = this._skyboxMaterial;
  92138. };
  92139. /**
  92140. * Setup the skybox reflection texture according to the specified options.
  92141. */
  92142. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  92143. if (!this._skyboxMaterial) {
  92144. return;
  92145. }
  92146. if (this._skyboxTexture) {
  92147. return;
  92148. }
  92149. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  92150. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92151. return;
  92152. }
  92153. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92154. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  92155. this._skyboxTexture.gammaSpace = false;
  92156. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92157. };
  92158. /**
  92159. * Dispose all the elements created by the Helper.
  92160. */
  92161. EnvironmentHelper.prototype.dispose = function () {
  92162. if (this._groundMaterial) {
  92163. this._groundMaterial.dispose(true, true);
  92164. }
  92165. if (this._skyboxMaterial) {
  92166. this._skyboxMaterial.dispose(true, true);
  92167. }
  92168. this._rootMesh.dispose(false);
  92169. };
  92170. /**
  92171. * Default ground texture URL.
  92172. */
  92173. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  92174. /**
  92175. * Default skybox texture URL.
  92176. */
  92177. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  92178. /**
  92179. * Default environment texture URL.
  92180. */
  92181. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  92182. return EnvironmentHelper;
  92183. }());
  92184. BABYLON.EnvironmentHelper = EnvironmentHelper;
  92185. })(BABYLON || (BABYLON = {}));
  92186. //# sourceMappingURL=babylon.environmentHelper.js.map
  92187. "use strict";
  92188. var BABYLON;
  92189. (function (BABYLON) {
  92190. /**
  92191. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  92192. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  92193. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  92194. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  92195. */
  92196. var VideoDome = /** @class */ (function (_super) {
  92197. __extends(VideoDome, _super);
  92198. /**
  92199. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  92200. * @param name Element's name, child elements will append suffixes for their own names.
  92201. * @param urlsOrVideo
  92202. * @param options An object containing optional or exposed sub element properties:
  92203. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  92204. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  92205. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  92206. * @param options **loop=true** Automatically loop video on end.
  92207. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  92208. */
  92209. function VideoDome(name, urlsOrVideo, options, scene) {
  92210. var _this = _super.call(this, name, scene) || this;
  92211. // set defaults and manage values
  92212. name = name || "videoDome";
  92213. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  92214. options.clickToPlay = Boolean(options.clickToPlay);
  92215. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  92216. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  92217. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  92218. // create
  92219. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  92220. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  92221. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  92222. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  92223. flat: false,
  92224. radius: options.size,
  92225. subdivisions: options.resolution,
  92226. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  92227. }, scene);
  92228. // configure material
  92229. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  92230. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  92231. material.reflectionTexture = _this._videoTexture;
  92232. material.useEquirectangularFOV = true;
  92233. material.fovMultiplier = 1.0;
  92234. // configure mesh
  92235. _this._mesh.material = material;
  92236. _this._mesh.parent = _this;
  92237. // optional configuration
  92238. if (options.clickToPlay) {
  92239. scene.onPointerUp = function () {
  92240. _this._videoTexture.video.play();
  92241. };
  92242. }
  92243. return _this;
  92244. }
  92245. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  92246. /**
  92247. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  92248. * Also see the options.resolution property.
  92249. */
  92250. get: function () {
  92251. return this._material.fovMultiplier;
  92252. },
  92253. set: function (value) {
  92254. this._material.fovMultiplier = value;
  92255. },
  92256. enumerable: true,
  92257. configurable: true
  92258. });
  92259. /**
  92260. * Releases resources associated with this node.
  92261. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  92262. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  92263. */
  92264. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  92265. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  92266. this._videoTexture.dispose();
  92267. this._mesh.dispose();
  92268. this._material.dispose();
  92269. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  92270. };
  92271. return VideoDome;
  92272. }(BABYLON.Node));
  92273. BABYLON.VideoDome = VideoDome;
  92274. })(BABYLON || (BABYLON = {}));
  92275. //# sourceMappingURL=babylon.videoDome.js.map
  92276. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#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\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb);\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\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/height;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(textureSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\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;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  92277. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  92278. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  92279. globalObject["BABYLON"] = BABYLON
  92280. return BABYLON;
  92281. });